1#![allow(unused)]
2mod blink_manager;
3pub mod display_map;
4mod editor_settings;
5mod element;
6mod inlay_hint_cache;
7
8mod git;
9mod highlight_matching_bracket;
10mod hover_popover;
11pub mod items;
12mod link_go_to_definition;
13mod mouse_context_menu;
14pub mod movement;
15mod persistence;
16pub mod scroll;
17pub mod selections_collection;
18
19#[cfg(test)]
20mod editor_tests;
21#[cfg(any(test, feature = "test-support"))]
22pub mod test;
23use aho_corasick::AhoCorasick;
24use anyhow::{Context as _, Result};
25use blink_manager::BlinkManager;
26use client::{ClickhouseEvent, Client, Collaborator, ParticipantIndex, TelemetrySettings};
27use clock::ReplicaId;
28use collections::{BTreeMap, HashMap, HashSet, VecDeque};
29use copilot::Copilot;
30pub use display_map::DisplayPoint;
31use display_map::*;
32pub use editor_settings::EditorSettings;
33pub use element::{
34 Cursor, EditorElement, HighlightedRange, HighlightedRangeLine, LineWithInvisibles,
35};
36use futures::FutureExt;
37use fuzzy::{StringMatch, StringMatchCandidate};
38use gpui::{
39 div, px, AnyElement, AppContext, BackgroundExecutor, Context, DispatchContext, Div, Element,
40 Entity, EventEmitter, FocusHandle, FontStyle, FontWeight, Hsla, Model, Pixels, Render, Styled,
41 Subscription, Task, TextStyle, View, ViewContext, VisualContext, WeakView, WindowContext,
42};
43use highlight_matching_bracket::refresh_matching_bracket_highlights;
44use hover_popover::{hide_hover, HoverState};
45use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
46pub use items::MAX_TAB_TITLE_LEN;
47use itertools::Itertools;
48pub use language::{char_kind, CharKind};
49use language::{
50 language_settings::{self, all_language_settings, InlayHintSettings},
51 point_from_lsp, AutoindentMode, BracketPair, Buffer, CodeAction, Completion, CursorShape,
52 Diagnostic, Language, LanguageRegistry, LanguageServerName, OffsetRangeExt, Point, Selection,
53 SelectionGoal, TransactionId,
54};
55use link_go_to_definition::{GoToDefinitionLink, InlayHighlight, LinkGoToDefinitionState};
56use lsp::{DiagnosticSeverity, Documentation, LanguageServerId};
57use movement::TextLayoutDetails;
58pub use multi_buffer::{
59 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
60 ToPoint,
61};
62use ordered_float::OrderedFloat;
63use parking_lot::RwLock;
64use project::{FormatTrigger, Location, Project};
65use rpc::proto::*;
66use scroll::{
67 autoscroll::Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide,
68};
69use selections_collection::{MutableSelectionsCollection, SelectionsCollection};
70use serde::{Deserialize, Serialize};
71use settings::{Settings, SettingsStore};
72use smallvec::SmallVec;
73use std::{
74 any::TypeId,
75 borrow::Cow,
76 cmp::{self, Ordering, Reverse},
77 ops::{ControlFlow, Deref, DerefMut, Range},
78 path::Path,
79 sync::Arc,
80 time::{Duration, Instant},
81};
82pub use sum_tree::Bias;
83use sum_tree::TreeMap;
84use text::Rope;
85use theme::{ActiveTheme, PlayerColor, ThemeColors, ThemeSettings, ThemeVariant};
86use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
87use workspace::{ItemNavHistory, SplitDirection, ViewId, Workspace};
88
89const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
90const MAX_LINE_LEN: usize = 1024;
91const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
92const MAX_SELECTION_HISTORY_LEN: usize = 1024;
93const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
94pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
95pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
96
97pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
98
99// pub fn render_parsed_markdown<Tag: 'static>(
100// parsed: &language::ParsedMarkdown,
101// editor_style: &EditorStyle,
102// workspace: Option<WeakView<Workspace>>,
103// cx: &mut ViewContext<Editor>,
104// ) -> Text {
105// enum RenderedMarkdown {}
106
107// let parsed = parsed.clone();
108// let view_id = cx.view_id();
109// let code_span_background_color = editor_style.document_highlight_read_background;
110
111// let mut region_id = 0;
112
113// todo!()
114// // Text::new(parsed.text, editor_style.text.clone())
115// // .with_highlights(
116// // parsed
117// // .highlights
118// // .iter()
119// // .filter_map(|(range, highlight)| {
120// // let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
121// // Some((range.clone(), highlight))
122// // })
123// // .collect::<Vec<_>>(),
124// // )
125// // .with_custom_runs(parsed.region_ranges, move |ix, bounds, cx| {
126// // region_id += 1;
127// // let region = parsed.regions[ix].clone();
128
129// // if let Some(link) = region.link {
130// // cx.scene().push_cursor_region(CursorRegion {
131// // bounds,
132// // style: CursorStyle::PointingHand,
133// // });
134// // cx.scene().push_mouse_region(
135// // MouseRegion::new::<(RenderedMarkdown, Tag)>(view_id, region_id, bounds)
136// // .on_down::<Editor, _>(MouseButton::Left, move |_, _, cx| match &link {
137// // markdown::Link::Web { url } => cx.platform().open_url(url),
138// // markdown::Link::Path { path } => {
139// // if let Some(workspace) = &workspace {
140// // _ = workspace.update(cx, |workspace, cx| {
141// // workspace.open_abs_path(path.clone(), false, cx).detach();
142// // });
143// // }
144// // }
145// // }),
146// // );
147// // }
148
149// // if region.code {
150// // cx.draw_quad(Quad {
151// // bounds,
152// // background: Some(code_span_background_color),
153// // corner_radii: (2.0).into(),
154// // order: todo!(),
155// // content_mask: todo!(),
156// // border_color: todo!(),
157// // border_widths: todo!(),
158// // });
159// // }
160// // })
161// // .with_soft_wrap(true)
162// }
163
164#[derive(Clone, Deserialize, PartialEq, Default)]
165pub struct SelectNext {
166 #[serde(default)]
167 pub replace_newest: bool,
168}
169
170#[derive(Clone, Deserialize, PartialEq, Default)]
171pub struct SelectPrevious {
172 #[serde(default)]
173 pub replace_newest: bool,
174}
175
176#[derive(Clone, Deserialize, PartialEq, Default)]
177pub struct SelectAllMatches {
178 #[serde(default)]
179 pub replace_newest: bool,
180}
181
182#[derive(Clone, Deserialize, PartialEq)]
183pub struct SelectToBeginningOfLine {
184 #[serde(default)]
185 stop_at_soft_wraps: bool,
186}
187
188#[derive(Clone, Default, Deserialize, PartialEq)]
189pub struct MovePageUp {
190 #[serde(default)]
191 center_cursor: bool,
192}
193
194#[derive(Clone, Default, Deserialize, PartialEq)]
195pub struct MovePageDown {
196 #[serde(default)]
197 center_cursor: bool,
198}
199
200#[derive(Clone, Deserialize, PartialEq)]
201pub struct SelectToEndOfLine {
202 #[serde(default)]
203 stop_at_soft_wraps: bool,
204}
205
206#[derive(Clone, Deserialize, PartialEq)]
207pub struct ToggleCodeActions {
208 #[serde(default)]
209 pub deployed_from_indicator: bool,
210}
211
212#[derive(Clone, Default, Deserialize, PartialEq)]
213pub struct ConfirmCompletion {
214 #[serde(default)]
215 pub item_ix: Option<usize>,
216}
217
218#[derive(Clone, Default, Deserialize, PartialEq)]
219pub struct ConfirmCodeAction {
220 #[serde(default)]
221 pub item_ix: Option<usize>,
222}
223
224#[derive(Clone, Default, Deserialize, PartialEq)]
225pub struct ToggleComments {
226 #[serde(default)]
227 pub advance_downwards: bool,
228}
229
230#[derive(Clone, Default, Deserialize, PartialEq)]
231pub struct FoldAt {
232 pub buffer_row: u32,
233}
234
235#[derive(Clone, Default, Deserialize, PartialEq)]
236pub struct UnfoldAt {
237 pub buffer_row: u32,
238}
239
240#[derive(Clone, Default, Deserialize, PartialEq)]
241pub struct GutterHover {
242 pub hovered: bool,
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub enum InlayId {
247 Suggestion(usize),
248 Hint(usize),
249}
250
251impl InlayId {
252 fn id(&self) -> usize {
253 match self {
254 Self::Suggestion(id) => *id,
255 Self::Hint(id) => *id,
256 }
257 }
258}
259
260// actions!(
261// editor,
262// [
263// Cancel,
264// Backspace,
265// Delete,
266// Newline,
267// NewlineAbove,
268// NewlineBelow,
269// GoToDiagnostic,
270// GoToPrevDiagnostic,
271// GoToHunk,
272// GoToPrevHunk,
273// Indent,
274// Outdent,
275// DeleteLine,
276// DeleteToPreviousWordStart,
277// DeleteToPreviousSubwordStart,
278// DeleteToNextWordEnd,
279// DeleteToNextSubwordEnd,
280// DeleteToBeginningOfLine,
281// DeleteToEndOfLine,
282// CutToEndOfLine,
283// DuplicateLine,
284// MoveLineUp,
285// MoveLineDown,
286// JoinLines,
287// SortLinesCaseSensitive,
288// SortLinesCaseInsensitive,
289// ReverseLines,
290// ShuffleLines,
291// ConvertToUpperCase,
292// ConvertToLowerCase,
293// ConvertToTitleCase,
294// ConvertToSnakeCase,
295// ConvertToKebabCase,
296// ConvertToUpperCamelCase,
297// ConvertToLowerCamelCase,
298// Transpose,
299// Cut,
300// Copy,
301// Paste,
302// Undo,
303// Redo,
304// MoveUp,
305// PageUp,
306// MoveDown,
307// PageDown,
308// MoveLeft,
309// MoveRight,
310// MoveToPreviousWordStart,
311// MoveToPreviousSubwordStart,
312// MoveToNextWordEnd,
313// MoveToNextSubwordEnd,
314// MoveToBeginningOfLine,
315// MoveToEndOfLine,
316// MoveToStartOfParagraph,
317// MoveToEndOfParagraph,
318// MoveToBeginning,
319// MoveToEnd,
320// SelectUp,
321// SelectDown,
322// SelectLeft,
323// SelectRight,
324// SelectToPreviousWordStart,
325// SelectToPreviousSubwordStart,
326// SelectToNextWordEnd,
327// SelectToNextSubwordEnd,
328// SelectToStartOfParagraph,
329// SelectToEndOfParagraph,
330// SelectToBeginning,
331// SelectToEnd,
332// SelectAll,
333// SelectLine,
334// SplitSelectionIntoLines,
335// AddSelectionAbove,
336// AddSelectionBelow,
337// Tab,
338// TabPrev,
339// ShowCharacterPalette,
340// SelectLargerSyntaxNode,
341// SelectSmallerSyntaxNode,
342// GoToDefinition,
343// GoToDefinitionSplit,
344// GoToTypeDefinition,
345// GoToTypeDefinitionSplit,
346// MoveToEnclosingBracket,
347// UndoSelection,
348// RedoSelection,
349// FindAllReferences,
350// Rename,
351// ConfirmRename,
352// Fold,
353// UnfoldLines,
354// FoldSelectedRanges,
355// ShowCompletions,
356// OpenExcerpts,
357// RestartLanguageServer,
358// Hover,
359// Format,
360// ToggleSoftWrap,
361// ToggleInlayHints,
362// RevealInFinder,
363// CopyPath,
364// CopyRelativePath,
365// CopyHighlightJson,
366// ContextMenuFirst,
367// ContextMenuPrev,
368// ContextMenuNext,
369// ContextMenuLast,
370// ]
371// );
372
373// impl_actions!(
374// editor,
375// [
376// SelectNext,
377// SelectPrevious,
378// SelectAllMatches,
379// SelectToBeginningOfLine,
380// SelectToEndOfLine,
381// ToggleCodeActions,
382// MovePageUp,
383// MovePageDown,
384// ConfirmCompletion,
385// ConfirmCodeAction,
386// ToggleComments,
387// FoldAt,
388// UnfoldAt,
389// GutterHover
390// ]
391// );
392
393// todo!(revisit these actions)
394pub struct ShowCompletions;
395pub struct Rename;
396pub struct GoToDefinition;
397pub struct GoToTypeDefinition;
398pub struct GoToDefinitionSplit;
399pub struct GoToTypeDefinitionSplit;
400
401#[derive(PartialEq, Clone, Default, Deserialize)]
402pub struct MoveLeft;
403
404#[derive(PartialEq, Clone, Default, Deserialize)]
405pub struct MoveRight;
406
407#[derive(PartialEq, Clone, Default, Deserialize)]
408pub struct MoveDown;
409
410#[derive(PartialEq, Clone, Default, Deserialize)]
411pub struct MoveUp;
412
413enum DocumentHighlightRead {}
414enum DocumentHighlightWrite {}
415enum InputComposition {}
416
417#[derive(Copy, Clone, PartialEq, Eq)]
418pub enum Direction {
419 Prev,
420 Next,
421}
422
423pub fn init_settings(cx: &mut AppContext) {
424 EditorSettings::register(cx);
425}
426
427pub fn init(cx: &mut AppContext) {
428 init_settings(cx);
429 // cx.register_action_type(Editor::new_file);
430 // cx.register_action_type(Editor::new_file_in_direction);
431 // cx.register_action_type(Editor::cancel);
432 // cx.register_action_type(Editor::newline);
433 // cx.register_action_type(Editor::newline_above);
434 // cx.register_action_type(Editor::newline_below);
435 // cx.register_action_type(Editor::backspace);
436 // cx.register_action_type(Editor::delete);
437 // cx.register_action_type(Editor::tab);
438 // cx.register_action_type(Editor::tab_prev);
439 // cx.register_action_type(Editor::indent);
440 // cx.register_action_type(Editor::outdent);
441 // cx.register_action_type(Editor::delete_line);
442 // cx.register_action_type(Editor::join_lines);
443 // cx.register_action_type(Editor::sort_lines_case_sensitive);
444 // cx.register_action_type(Editor::sort_lines_case_insensitive);
445 // cx.register_action_type(Editor::reverse_lines);
446 // cx.register_action_type(Editor::shuffle_lines);
447 // cx.register_action_type(Editor::convert_to_upper_case);
448 // cx.register_action_type(Editor::convert_to_lower_case);
449 // cx.register_action_type(Editor::convert_to_title_case);
450 // cx.register_action_type(Editor::convert_to_snake_case);
451 // cx.register_action_type(Editor::convert_to_kebab_case);
452 // cx.register_action_type(Editor::convert_to_upper_camel_case);
453 // cx.register_action_type(Editor::convert_to_lower_camel_case);
454 // cx.register_action_type(Editor::delete_to_previous_word_start);
455 // cx.register_action_type(Editor::delete_to_previous_subword_start);
456 // cx.register_action_type(Editor::delete_to_next_word_end);
457 // cx.register_action_type(Editor::delete_to_next_subword_end);
458 // cx.register_action_type(Editor::delete_to_beginning_of_line);
459 // cx.register_action_type(Editor::delete_to_end_of_line);
460 // cx.register_action_type(Editor::cut_to_end_of_line);
461 // cx.register_action_type(Editor::duplicate_line);
462 // cx.register_action_type(Editor::move_line_up);
463 // cx.register_action_type(Editor::move_line_down);
464 // cx.register_action_type(Editor::transpose);
465 // cx.register_action_type(Editor::cut);
466 // cx.register_action_type(Editor::copy);
467 // cx.register_action_type(Editor::paste);
468 // cx.register_action_type(Editor::undo);
469 // cx.register_action_type(Editor::redo);
470 cx.register_action_type::<MoveUp>();
471 // cx.register_action_type(Editor::move_page_up);
472 cx.register_action_type::<MoveDown>();
473 // cx.register_action_type(Editor::move_page_down);
474 // cx.register_action_type(Editor::next_screen);
475 cx.register_action_type::<MoveLeft>();
476 cx.register_action_type::<MoveRight>();
477 // cx.register_action_type(Editor::move_to_previous_word_start);
478 // cx.register_action_type(Editor::move_to_previous_subword_start);
479 // cx.register_action_type(Editor::move_to_next_word_end);
480 // cx.register_action_type(Editor::move_to_next_subword_end);
481 // cx.register_action_type(Editor::move_to_beginning_of_line);
482 // cx.register_action_type(Editor::move_to_end_of_line);
483 // cx.register_action_type(Editor::move_to_start_of_paragraph);
484 // cx.register_action_type(Editor::move_to_end_of_paragraph);
485 // cx.register_action_type(Editor::move_to_beginning);
486 // cx.register_action_type(Editor::move_to_end);
487 // cx.register_action_type(Editor::select_up);
488 // cx.register_action_type(Editor::select_down);
489 // cx.register_action_type(Editor::select_left);
490 // cx.register_action_type(Editor::select_right);
491 // cx.register_action_type(Editor::select_to_previous_word_start);
492 // cx.register_action_type(Editor::select_to_previous_subword_start);
493 // cx.register_action_type(Editor::select_to_next_word_end);
494 // cx.register_action_type(Editor::select_to_next_subword_end);
495 // cx.register_action_type(Editor::select_to_beginning_of_line);
496 // cx.register_action_type(Editor::select_to_end_of_line);
497 // cx.register_action_type(Editor::select_to_start_of_paragraph);
498 // cx.register_action_type(Editor::select_to_end_of_paragraph);
499 // cx.register_action_type(Editor::select_to_beginning);
500 // cx.register_action_type(Editor::select_to_end);
501 // cx.register_action_type(Editor::select_all);
502 // cx.register_action_type(Editor::select_all_matches);
503 // cx.register_action_type(Editor::select_line);
504 // cx.register_action_type(Editor::split_selection_into_lines);
505 // cx.register_action_type(Editor::add_selection_above);
506 // cx.register_action_type(Editor::add_selection_below);
507 // cx.register_action_type(Editor::select_next);
508 // cx.register_action_type(Editor::select_previous);
509 // cx.register_action_type(Editor::toggle_comments);
510 // cx.register_action_type(Editor::select_larger_syntax_node);
511 // cx.register_action_type(Editor::select_smaller_syntax_node);
512 // cx.register_action_type(Editor::move_to_enclosing_bracket);
513 // cx.register_action_type(Editor::undo_selection);
514 // cx.register_action_type(Editor::redo_selection);
515 // cx.register_action_type(Editor::go_to_diagnostic);
516 // cx.register_action_type(Editor::go_to_prev_diagnostic);
517 // cx.register_action_type(Editor::go_to_hunk);
518 // cx.register_action_type(Editor::go_to_prev_hunk);
519 // cx.register_action_type(Editor::go_to_definition);
520 // cx.register_action_type(Editor::go_to_definition_split);
521 // cx.register_action_type(Editor::go_to_type_definition);
522 // cx.register_action_type(Editor::go_to_type_definition_split);
523 // cx.register_action_type(Editor::fold);
524 // cx.register_action_type(Editor::fold_at);
525 // cx.register_action_type(Editor::unfold_lines);
526 // cx.register_action_type(Editor::unfold_at);
527 // cx.register_action_type(Editor::gutter_hover);
528 // cx.register_action_type(Editor::fold_selected_ranges);
529 // cx.register_action_type(Editor::show_completions);
530 // cx.register_action_type(Editor::toggle_code_actions);
531 // cx.register_action_type(Editor::open_excerpts);
532 // cx.register_action_type(Editor::toggle_soft_wrap);
533 // cx.register_action_type(Editor::toggle_inlay_hints);
534 // cx.register_action_type(Editor::reveal_in_finder);
535 // cx.register_action_type(Editor::copy_path);
536 // cx.register_action_type(Editor::copy_relative_path);
537 // cx.register_action_type(Editor::copy_highlight_json);
538 // cx.add_async_action(Editor::format);
539 // cx.register_action_type(Editor::restart_language_server);
540 // cx.register_action_type(Editor::show_character_palette);
541 // cx.add_async_action(Editor::confirm_completion);
542 // cx.add_async_action(Editor::confirm_code_action);
543 // cx.add_async_action(Editor::rename);
544 // cx.add_async_action(Editor::confirm_rename);
545 // cx.add_async_action(Editor::find_all_references);
546 // cx.register_action_type(Editor::next_copilot_suggestion);
547 // cx.register_action_type(Editor::previous_copilot_suggestion);
548 // cx.register_action_type(Editor::copilot_suggest);
549 // cx.register_action_type(Editor::context_menu_first);
550 // cx.register_action_type(Editor::context_menu_prev);
551 // cx.register_action_type(Editor::context_menu_next);
552 // cx.register_action_type(Editor::context_menu_last);
553
554 hover_popover::init(cx);
555 scroll::actions::init(cx);
556
557 workspace::register_project_item::<Editor>(cx);
558 workspace::register_followable_item::<Editor>(cx);
559 workspace::register_deserializable_item::<Editor>(cx);
560}
561
562trait InvalidationRegion {
563 fn ranges(&self) -> &[Range<Anchor>];
564}
565
566#[derive(Clone, Debug, PartialEq)]
567pub enum SelectPhase {
568 Begin {
569 position: DisplayPoint,
570 add: bool,
571 click_count: usize,
572 },
573 BeginColumnar {
574 position: DisplayPoint,
575 goal_column: u32,
576 },
577 Extend {
578 position: DisplayPoint,
579 click_count: usize,
580 },
581 Update {
582 position: DisplayPoint,
583 goal_column: u32,
584 scroll_position: gpui::Point<f32>,
585 },
586 End,
587}
588
589#[derive(Clone, Debug)]
590pub enum SelectMode {
591 Character,
592 Word(Range<Anchor>),
593 Line(Range<Anchor>),
594 All,
595}
596
597#[derive(Copy, Clone, PartialEq, Eq, Debug)]
598pub enum EditorMode {
599 SingleLine,
600 AutoHeight { max_lines: usize },
601 Full,
602}
603
604#[derive(Clone, Debug)]
605pub enum SoftWrap {
606 None,
607 EditorWidth,
608 Column(u32),
609}
610
611#[derive(Clone)]
612pub struct EditorStyle {
613 pub background: Hsla,
614 pub local_player: PlayerColor,
615 pub text: TextStyle,
616 pub line_height_scalar: f32,
617 pub scrollbar_width: Pixels,
618}
619
620type CompletionId = usize;
621
622// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
623// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
624
625type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
626type InlayBackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<InlayHighlight>);
627
628pub struct Editor {
629 handle: WeakView<Self>,
630 focus_handle: FocusHandle,
631 buffer: Model<MultiBuffer>,
632 display_map: Model<DisplayMap>,
633 pub selections: SelectionsCollection,
634 pub scroll_manager: ScrollManager,
635 columnar_selection_tail: Option<Anchor>,
636 add_selections_state: Option<AddSelectionsState>,
637 select_next_state: Option<SelectNextState>,
638 select_prev_state: Option<SelectNextState>,
639 selection_history: SelectionHistory,
640 autoclose_regions: Vec<AutocloseRegion>,
641 snippet_stack: InvalidationStack<SnippetState>,
642 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
643 ime_transaction: Option<TransactionId>,
644 active_diagnostics: Option<ActiveDiagnosticGroup>,
645 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
646 // get_field_editor_theme: Option<Arc<GetFieldEditorTheme>>,
647 // override_text_style: Option<Box<OverrideTextStyle>>,
648 project: Option<Model<Project>>,
649 collaboration_hub: Option<Box<dyn CollaborationHub>>,
650 blink_manager: Model<BlinkManager>,
651 pub show_local_selections: bool,
652 mode: EditorMode,
653 show_gutter: bool,
654 show_wrap_guides: Option<bool>,
655 placeholder_text: Option<Arc<str>>,
656 highlighted_rows: Option<Range<u32>>,
657 background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
658 inlay_background_highlights: TreeMap<Option<TypeId>, InlayBackgroundHighlight>,
659 nav_history: Option<ItemNavHistory>,
660 context_menu: RwLock<Option<ContextMenu>>,
661 // mouse_context_menu: View<context_menu::ContextMenu>,
662 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
663 next_completion_id: CompletionId,
664 available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
665 code_actions_task: Option<Task<()>>,
666 document_highlights_task: Option<Task<()>>,
667 pending_rename: Option<RenameState>,
668 searchable: bool,
669 cursor_shape: CursorShape,
670 collapse_matches: bool,
671 autoindent_mode: Option<AutoindentMode>,
672 workspace: Option<(WeakView<Workspace>, i64)>,
673 keymap_context_layers: BTreeMap<TypeId, DispatchContext>,
674 input_enabled: bool,
675 read_only: bool,
676 leader_peer_id: Option<PeerId>,
677 remote_id: Option<ViewId>,
678 hover_state: HoverState,
679 gutter_hovered: bool,
680 link_go_to_definition_state: LinkGoToDefinitionState,
681 copilot_state: CopilotState,
682 inlay_hint_cache: InlayHintCache,
683 next_inlay_id: usize,
684 _subscriptions: Vec<Subscription>,
685 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
686 style: Option<EditorStyle>,
687}
688
689pub struct EditorSnapshot {
690 pub mode: EditorMode,
691 pub show_gutter: bool,
692 pub display_snapshot: DisplaySnapshot,
693 pub placeholder_text: Option<Arc<str>>,
694 is_focused: bool,
695 scroll_anchor: ScrollAnchor,
696 ongoing_scroll: OngoingScroll,
697}
698
699pub struct RemoteSelection {
700 pub replica_id: ReplicaId,
701 pub selection: Selection<Anchor>,
702 pub cursor_shape: CursorShape,
703 pub peer_id: PeerId,
704 pub line_mode: bool,
705 pub participant_index: Option<ParticipantIndex>,
706}
707
708#[derive(Clone, Debug)]
709struct SelectionHistoryEntry {
710 selections: Arc<[Selection<Anchor>]>,
711 select_next_state: Option<SelectNextState>,
712 select_prev_state: Option<SelectNextState>,
713 add_selections_state: Option<AddSelectionsState>,
714}
715
716enum SelectionHistoryMode {
717 Normal,
718 Undoing,
719 Redoing,
720}
721
722impl Default for SelectionHistoryMode {
723 fn default() -> Self {
724 Self::Normal
725 }
726}
727
728#[derive(Default)]
729struct SelectionHistory {
730 #[allow(clippy::type_complexity)]
731 selections_by_transaction:
732 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
733 mode: SelectionHistoryMode,
734 undo_stack: VecDeque<SelectionHistoryEntry>,
735 redo_stack: VecDeque<SelectionHistoryEntry>,
736}
737
738impl SelectionHistory {
739 fn insert_transaction(
740 &mut self,
741 transaction_id: TransactionId,
742 selections: Arc<[Selection<Anchor>]>,
743 ) {
744 self.selections_by_transaction
745 .insert(transaction_id, (selections, None));
746 }
747
748 #[allow(clippy::type_complexity)]
749 fn transaction(
750 &self,
751 transaction_id: TransactionId,
752 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
753 self.selections_by_transaction.get(&transaction_id)
754 }
755
756 #[allow(clippy::type_complexity)]
757 fn transaction_mut(
758 &mut self,
759 transaction_id: TransactionId,
760 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
761 self.selections_by_transaction.get_mut(&transaction_id)
762 }
763
764 fn push(&mut self, entry: SelectionHistoryEntry) {
765 if !entry.selections.is_empty() {
766 match self.mode {
767 SelectionHistoryMode::Normal => {
768 self.push_undo(entry);
769 self.redo_stack.clear();
770 }
771 SelectionHistoryMode::Undoing => self.push_redo(entry),
772 SelectionHistoryMode::Redoing => self.push_undo(entry),
773 }
774 }
775 }
776
777 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
778 if self
779 .undo_stack
780 .back()
781 .map_or(true, |e| e.selections != entry.selections)
782 {
783 self.undo_stack.push_back(entry);
784 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
785 self.undo_stack.pop_front();
786 }
787 }
788 }
789
790 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
791 if self
792 .redo_stack
793 .back()
794 .map_or(true, |e| e.selections != entry.selections)
795 {
796 self.redo_stack.push_back(entry);
797 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
798 self.redo_stack.pop_front();
799 }
800 }
801 }
802}
803
804#[derive(Clone, Debug)]
805struct AddSelectionsState {
806 above: bool,
807 stack: Vec<usize>,
808}
809
810#[derive(Clone)]
811struct SelectNextState {
812 query: AhoCorasick,
813 wordwise: bool,
814 done: bool,
815}
816
817impl std::fmt::Debug for SelectNextState {
818 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819 f.debug_struct(std::any::type_name::<Self>())
820 .field("wordwise", &self.wordwise)
821 .field("done", &self.done)
822 .finish()
823 }
824}
825
826#[derive(Debug)]
827struct AutocloseRegion {
828 selection_id: usize,
829 range: Range<Anchor>,
830 pair: BracketPair,
831}
832
833#[derive(Debug)]
834struct SnippetState {
835 ranges: Vec<Vec<Range<Anchor>>>,
836 active_index: usize,
837}
838
839pub struct RenameState {
840 pub range: Range<Anchor>,
841 pub old_name: Arc<str>,
842 pub editor: View<Editor>,
843 block_id: BlockId,
844}
845
846struct InvalidationStack<T>(Vec<T>);
847
848enum ContextMenu {
849 Completions(CompletionsMenu),
850 CodeActions(CodeActionsMenu),
851}
852
853impl ContextMenu {
854 fn select_first(
855 &mut self,
856 project: Option<&Model<Project>>,
857 cx: &mut ViewContext<Editor>,
858 ) -> bool {
859 if self.visible() {
860 match self {
861 ContextMenu::Completions(menu) => menu.select_first(project, cx),
862 ContextMenu::CodeActions(menu) => menu.select_first(cx),
863 }
864 true
865 } else {
866 false
867 }
868 }
869
870 fn select_prev(
871 &mut self,
872 project: Option<&Model<Project>>,
873 cx: &mut ViewContext<Editor>,
874 ) -> bool {
875 if self.visible() {
876 match self {
877 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
878 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
879 }
880 true
881 } else {
882 false
883 }
884 }
885
886 fn select_next(
887 &mut self,
888 project: Option<&Model<Project>>,
889 cx: &mut ViewContext<Editor>,
890 ) -> bool {
891 if self.visible() {
892 match self {
893 ContextMenu::Completions(menu) => menu.select_next(project, cx),
894 ContextMenu::CodeActions(menu) => menu.select_next(cx),
895 }
896 true
897 } else {
898 false
899 }
900 }
901
902 fn select_last(
903 &mut self,
904 project: Option<&Model<Project>>,
905 cx: &mut ViewContext<Editor>,
906 ) -> bool {
907 if self.visible() {
908 match self {
909 ContextMenu::Completions(menu) => menu.select_last(project, cx),
910 ContextMenu::CodeActions(menu) => menu.select_last(cx),
911 }
912 true
913 } else {
914 false
915 }
916 }
917
918 fn visible(&self) -> bool {
919 match self {
920 ContextMenu::Completions(menu) => menu.visible(),
921 ContextMenu::CodeActions(menu) => menu.visible(),
922 }
923 }
924
925 fn render(
926 &self,
927 cursor_position: DisplayPoint,
928 style: EditorStyle,
929 workspace: Option<WeakView<Workspace>>,
930 cx: &mut ViewContext<Editor>,
931 ) -> (DisplayPoint, AnyElement<Editor>) {
932 todo!()
933 // match self {
934 // ContextMenu::Completions(menu) => (cursor_position, menu.render(style, workspace, cx)),
935 // ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, cx),
936 // }
937 }
938}
939
940#[derive(Clone)]
941struct CompletionsMenu {
942 id: CompletionId,
943 initial_position: Anchor,
944 buffer: Model<Buffer>,
945 completions: Arc<RwLock<Box<[Completion]>>>,
946 match_candidates: Arc<[StringMatchCandidate]>,
947 matches: Arc<[StringMatch]>,
948 selected_item: usize,
949 list: UniformListState,
950}
951
952// todo!(this is fake)
953#[derive(Clone, Default)]
954struct UniformListState;
955
956// todo!(this is fake)
957impl UniformListState {
958 pub fn scroll_to(&mut self, target: ScrollTarget) {}
959}
960
961// todo!(this is somewhat fake)
962#[derive(Debug)]
963pub enum ScrollTarget {
964 Show(usize),
965 Center(usize),
966}
967
968impl CompletionsMenu {
969 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
970 self.selected_item = 0;
971 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
972 self.attempt_resolve_selected_completion_documentation(project, cx);
973 cx.notify();
974 }
975
976 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
977 if self.selected_item > 0 {
978 self.selected_item -= 1;
979 } else {
980 self.selected_item = self.matches.len() - 1;
981 }
982 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
983 self.attempt_resolve_selected_completion_documentation(project, cx);
984 cx.notify();
985 }
986
987 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
988 if self.selected_item + 1 < self.matches.len() {
989 self.selected_item += 1;
990 } else {
991 self.selected_item = 0;
992 }
993 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
994 self.attempt_resolve_selected_completion_documentation(project, cx);
995 cx.notify();
996 }
997
998 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
999 self.selected_item = self.matches.len() - 1;
1000 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1001 self.attempt_resolve_selected_completion_documentation(project, cx);
1002 cx.notify();
1003 }
1004
1005 fn pre_resolve_completion_documentation(
1006 &self,
1007 project: Option<Model<Project>>,
1008 cx: &mut ViewContext<Editor>,
1009 ) {
1010 todo!("implementation below ");
1011 }
1012 // ) {
1013 // let settings = EditorSettings::get_global(cx);
1014 // if !settings.show_completion_documentation {
1015 // return;
1016 // }
1017
1018 // let Some(project) = project else {
1019 // return;
1020 // };
1021 // let client = project.read(cx).client();
1022 // let language_registry = project.read(cx).languages().clone();
1023
1024 // let is_remote = project.read(cx).is_remote();
1025 // let project_id = project.read(cx).remote_id();
1026
1027 // let completions = self.completions.clone();
1028 // let completion_indices: Vec<_> = self.matches.iter().map(|m| m.candidate_id).collect();
1029
1030 // cx.spawn(move |this, mut cx| async move {
1031 // if is_remote {
1032 // let Some(project_id) = project_id else {
1033 // log::error!("Remote project without remote_id");
1034 // return;
1035 // };
1036
1037 // for completion_index in completion_indices {
1038 // let completions_guard = completions.read();
1039 // let completion = &completions_guard[completion_index];
1040 // if completion.documentation.is_some() {
1041 // continue;
1042 // }
1043
1044 // let server_id = completion.server_id;
1045 // let completion = completion.lsp_completion.clone();
1046 // drop(completions_guard);
1047
1048 // Self::resolve_completion_documentation_remote(
1049 // project_id,
1050 // server_id,
1051 // completions.clone(),
1052 // completion_index,
1053 // completion,
1054 // client.clone(),
1055 // language_registry.clone(),
1056 // )
1057 // .await;
1058
1059 // _ = this.update(&mut cx, |_, cx| cx.notify());
1060 // }
1061 // } else {
1062 // for completion_index in completion_indices {
1063 // let completions_guard = completions.read();
1064 // let completion = &completions_guard[completion_index];
1065 // if completion.documentation.is_some() {
1066 // continue;
1067 // }
1068
1069 // let server_id = completion.server_id;
1070 // let completion = completion.lsp_completion.clone();
1071 // drop(completions_guard);
1072
1073 // let server = project.read_with(&mut cx, |project, _| {
1074 // project.language_server_for_id(server_id)
1075 // });
1076 // let Some(server) = server else {
1077 // return;
1078 // };
1079
1080 // Self::resolve_completion_documentation_local(
1081 // server,
1082 // completions.clone(),
1083 // completion_index,
1084 // completion,
1085 // language_registry.clone(),
1086 // )
1087 // .await;
1088
1089 // _ = this.update(&mut cx, |_, cx| cx.notify());
1090 // }
1091 // }
1092 // })
1093 // .detach();
1094 // }
1095
1096 fn attempt_resolve_selected_completion_documentation(
1097 &mut self,
1098 project: Option<&Model<Project>>,
1099 cx: &mut ViewContext<Editor>,
1100 ) {
1101 let settings = EditorSettings::get_global(cx);
1102 if !settings.show_completion_documentation {
1103 return;
1104 }
1105
1106 let completion_index = self.matches[self.selected_item].candidate_id;
1107 let Some(project) = project else {
1108 return;
1109 };
1110 let language_registry = project.read(cx).languages().clone();
1111
1112 let completions = self.completions.clone();
1113 let completions_guard = completions.read();
1114 let completion = &completions_guard[completion_index];
1115 // todo!()
1116 // if completion.documentation.is_some() {
1117 // return;
1118 // }
1119
1120 let server_id = completion.server_id;
1121 let completion = completion.lsp_completion.clone();
1122 drop(completions_guard);
1123
1124 if project.read(cx).is_remote() {
1125 let Some(project_id) = project.read(cx).remote_id() else {
1126 log::error!("Remote project without remote_id");
1127 return;
1128 };
1129
1130 let client = project.read(cx).client();
1131
1132 cx.spawn(move |this, mut cx| async move {
1133 Self::resolve_completion_documentation_remote(
1134 project_id,
1135 server_id,
1136 completions.clone(),
1137 completion_index,
1138 completion,
1139 client,
1140 language_registry.clone(),
1141 )
1142 .await;
1143
1144 _ = this.update(&mut cx, |_, cx| cx.notify());
1145 })
1146 .detach();
1147 } else {
1148 let Some(server) = project.read(cx).language_server_for_id(server_id) else {
1149 return;
1150 };
1151
1152 cx.spawn(move |this, mut cx| async move {
1153 Self::resolve_completion_documentation_local(
1154 server,
1155 completions,
1156 completion_index,
1157 completion,
1158 language_registry,
1159 )
1160 .await;
1161
1162 _ = this.update(&mut cx, |_, cx| cx.notify());
1163 })
1164 .detach();
1165 }
1166 }
1167
1168 async fn resolve_completion_documentation_remote(
1169 project_id: u64,
1170 server_id: LanguageServerId,
1171 completions: Arc<RwLock<Box<[Completion]>>>,
1172 completion_index: usize,
1173 completion: lsp::CompletionItem,
1174 client: Arc<Client>,
1175 language_registry: Arc<LanguageRegistry>,
1176 ) {
1177 todo!()
1178 // let request = proto::ResolveCompletionDocumentation {
1179 // project_id,
1180 // language_server_id: server_id.0 as u64,
1181 // lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
1182 // };
1183
1184 // let Some(response) = client
1185 // .request(request)
1186 // .await
1187 // .context("completion documentation resolve proto request")
1188 // .log_err()
1189 // else {
1190 // return;
1191 // };
1192
1193 // if response.text.is_empty() {
1194 // let mut completions = completions.write();
1195 // let completion = &mut completions[completion_index];
1196 // completion.documentation = Some(Documentation::Undocumented);
1197 // }
1198
1199 // let documentation = if response.is_markdown {
1200 // Documentation::MultiLineMarkdown(
1201 // markdown::parse_markdown(&response.text, &language_registry, None).await,
1202 // )
1203 // } else if response.text.lines().count() <= 1 {
1204 // Documentation::SingleLine(response.text)
1205 // } else {
1206 // Documentation::MultiLinePlainText(response.text)
1207 // };
1208
1209 // let mut completions = completions.write();
1210 // let completion = &mut completions[completion_index];
1211 // completion.documentation = Some(documentation);
1212 }
1213
1214 async fn resolve_completion_documentation_local(
1215 server: Arc<lsp::LanguageServer>,
1216 completions: Arc<RwLock<Box<[Completion]>>>,
1217 completion_index: usize,
1218 completion: lsp::CompletionItem,
1219 language_registry: Arc<LanguageRegistry>,
1220 ) {
1221 todo!()
1222 // let can_resolve = server
1223 // .capabilities()
1224 // .completion_provider
1225 // .as_ref()
1226 // .and_then(|options| options.resolve_provider)
1227 // .unwrap_or(false);
1228 // if !can_resolve {
1229 // return;
1230 // }
1231
1232 // let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
1233 // let Some(completion_item) = request.await.log_err() else {
1234 // return;
1235 // };
1236
1237 // if let Some(lsp_documentation) = completion_item.documentation {
1238 // let documentation = language::prepare_completion_documentation(
1239 // &lsp_documentation,
1240 // &language_registry,
1241 // None, // TODO: Try to reasonably work out which language the completion is for
1242 // )
1243 // .await;
1244
1245 // let mut completions = completions.write();
1246 // let completion = &mut completions[completion_index];
1247 // completion.documentation = Some(documentation);
1248 // } else {
1249 // let mut completions = completions.write();
1250 // let completion = &mut completions[completion_index];
1251 // completion.documentation = Some(Documentation::Undocumented);
1252 // }
1253 }
1254
1255 fn visible(&self) -> bool {
1256 !self.matches.is_empty()
1257 }
1258
1259 fn render(
1260 &self,
1261 style: EditorStyle,
1262 workspace: Option<WeakView<Workspace>>,
1263 cx: &mut ViewContext<Editor>,
1264 ) {
1265 todo!("old implementation below")
1266 }
1267 // ) -> AnyElement<Editor> {
1268 // enum CompletionTag {}
1269
1270 // let settings = EditorSettings>(cx);
1271 // let show_completion_documentation = settings.show_completion_documentation;
1272
1273 // let widest_completion_ix = self
1274 // .matches
1275 // .iter()
1276 // .enumerate()
1277 // .max_by_key(|(_, mat)| {
1278 // let completions = self.completions.read();
1279 // let completion = &completions[mat.candidate_id];
1280 // let documentation = &completion.documentation;
1281
1282 // let mut len = completion.label.text.chars().count();
1283 // if let Some(Documentation::SingleLine(text)) = documentation {
1284 // if show_completion_documentation {
1285 // len += text.chars().count();
1286 // }
1287 // }
1288
1289 // len
1290 // })
1291 // .map(|(ix, _)| ix);
1292
1293 // let completions = self.completions.clone();
1294 // let matches = self.matches.clone();
1295 // let selected_item = self.selected_item;
1296
1297 // let list = UniformList::new(self.list.clone(), matches.len(), cx, {
1298 // let style = style.clone();
1299 // move |_, range, items, cx| {
1300 // let start_ix = range.start;
1301 // let completions_guard = completions.read();
1302
1303 // for (ix, mat) in matches[range].iter().enumerate() {
1304 // let item_ix = start_ix + ix;
1305 // let candidate_id = mat.candidate_id;
1306 // let completion = &completions_guard[candidate_id];
1307
1308 // let documentation = if show_completion_documentation {
1309 // &completion.documentation
1310 // } else {
1311 // &None
1312 // };
1313
1314 // items.push(
1315 // MouseEventHandler::new::<CompletionTag, _>(
1316 // mat.candidate_id,
1317 // cx,
1318 // |state, _| {
1319 // let item_style = if item_ix == selected_item {
1320 // style.autocomplete.selected_item
1321 // } else if state.hovered() {
1322 // style.autocomplete.hovered_item
1323 // } else {
1324 // style.autocomplete.item
1325 // };
1326
1327 // let completion_label =
1328 // Text::new(completion.label.text.clone(), style.text.clone())
1329 // .with_soft_wrap(false)
1330 // .with_highlights(
1331 // combine_syntax_and_fuzzy_match_highlights(
1332 // &completion.label.text,
1333 // style.text.color.into(),
1334 // styled_runs_for_code_label(
1335 // &completion.label,
1336 // &style.syntax,
1337 // ),
1338 // &mat.positions,
1339 // ),
1340 // );
1341
1342 // if let Some(Documentation::SingleLine(text)) = documentation {
1343 // Flex::row()
1344 // .with_child(completion_label)
1345 // .with_children((|| {
1346 // let text_style = TextStyle {
1347 // color: style.autocomplete.inline_docs_color,
1348 // font_size: style.text.font_size
1349 // * style.autocomplete.inline_docs_size_percent,
1350 // ..style.text.clone()
1351 // };
1352
1353 // let label = Text::new(text.clone(), text_style)
1354 // .aligned()
1355 // .constrained()
1356 // .dynamically(move |constraint, _, _| {
1357 // gpui::SizeConstraint {
1358 // min: constraint.min,
1359 // max: vec2f(
1360 // constraint.max.x(),
1361 // constraint.min.y(),
1362 // ),
1363 // }
1364 // });
1365
1366 // if Some(item_ix) == widest_completion_ix {
1367 // Some(
1368 // label
1369 // .contained()
1370 // .with_style(
1371 // style
1372 // .autocomplete
1373 // .inline_docs_container,
1374 // )
1375 // .into_any(),
1376 // )
1377 // } else {
1378 // Some(label.flex_float().into_any())
1379 // }
1380 // })())
1381 // .into_any()
1382 // } else {
1383 // completion_label.into_any()
1384 // }
1385 // .contained()
1386 // .with_style(item_style)
1387 // .constrained()
1388 // .dynamically(
1389 // move |constraint, _, _| {
1390 // if Some(item_ix) == widest_completion_ix {
1391 // constraint
1392 // } else {
1393 // gpui::SizeConstraint {
1394 // min: constraint.min,
1395 // max: constraint.min,
1396 // }
1397 // }
1398 // },
1399 // )
1400 // },
1401 // )
1402 // .with_cursor_style(CursorStyle::PointingHand)
1403 // .on_down(MouseButton::Left, move |_, this, cx| {
1404 // this.confirm_completion(
1405 // &ConfirmCompletion {
1406 // item_ix: Some(item_ix),
1407 // },
1408 // cx,
1409 // )
1410 // .map(|task| task.detach());
1411 // })
1412 // .constrained()
1413 // .with_min_width(style.autocomplete.completion_min_width)
1414 // .with_max_width(style.autocomplete.completion_max_width)
1415 // .into_any(),
1416 // );
1417 // }
1418 // }
1419 // })
1420 // .with_width_from_item(widest_completion_ix);
1421
1422 // enum MultiLineDocumentation {}
1423
1424 // Flex::row()
1425 // .with_child(list.flex(1., false))
1426 // .with_children({
1427 // let mat = &self.matches[selected_item];
1428 // let completions = self.completions.read();
1429 // let completion = &completions[mat.candidate_id];
1430 // let documentation = &completion.documentation;
1431
1432 // match documentation {
1433 // Some(Documentation::MultiLinePlainText(text)) => Some(
1434 // Flex::column()
1435 // .scrollable::<MultiLineDocumentation>(0, None, cx)
1436 // .with_child(
1437 // Text::new(text.clone(), style.text.clone()).with_soft_wrap(true),
1438 // )
1439 // .contained()
1440 // .with_style(style.autocomplete.alongside_docs_container)
1441 // .constrained()
1442 // .with_max_width(style.autocomplete.alongside_docs_max_width)
1443 // .flex(1., false),
1444 // ),
1445
1446 // Some(Documentation::MultiLineMarkdown(parsed)) => Some(
1447 // Flex::column()
1448 // .scrollable::<MultiLineDocumentation>(0, None, cx)
1449 // .with_child(render_parsed_markdown::<MultiLineDocumentation>(
1450 // parsed, &style, workspace, cx,
1451 // ))
1452 // .contained()
1453 // .with_style(style.autocomplete.alongside_docs_container)
1454 // .constrained()
1455 // .with_max_width(style.autocomplete.alongside_docs_max_width)
1456 // .flex(1., false),
1457 // ),
1458
1459 // _ => None,
1460 // }
1461 // })
1462 // .contained()
1463 // .with_style(style.autocomplete.container)
1464 // .into_any()
1465 // }
1466
1467 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1468 let mut matches = if let Some(query) = query {
1469 fuzzy::match_strings(
1470 &self.match_candidates,
1471 query,
1472 query.chars().any(|c| c.is_uppercase()),
1473 100,
1474 &Default::default(),
1475 executor,
1476 )
1477 .await
1478 } else {
1479 self.match_candidates
1480 .iter()
1481 .enumerate()
1482 .map(|(candidate_id, candidate)| StringMatch {
1483 candidate_id,
1484 score: Default::default(),
1485 positions: Default::default(),
1486 string: candidate.string.clone(),
1487 })
1488 .collect()
1489 };
1490
1491 // Remove all candidates where the query's start does not match the start of any word in the candidate
1492 if let Some(query) = query {
1493 if let Some(query_start) = query.chars().next() {
1494 matches.retain(|string_match| {
1495 split_words(&string_match.string).any(|word| {
1496 // Check that the first codepoint of the word as lowercase matches the first
1497 // codepoint of the query as lowercase
1498 word.chars()
1499 .flat_map(|codepoint| codepoint.to_lowercase())
1500 .zip(query_start.to_lowercase())
1501 .all(|(word_cp, query_cp)| word_cp == query_cp)
1502 })
1503 });
1504 }
1505 }
1506
1507 let completions = self.completions.read();
1508 matches.sort_unstable_by_key(|mat| {
1509 let completion = &completions[mat.candidate_id];
1510 (
1511 completion.lsp_completion.sort_text.as_ref(),
1512 Reverse(OrderedFloat(mat.score)),
1513 completion.sort_key(),
1514 )
1515 });
1516 drop(completions);
1517
1518 for mat in &mut matches {
1519 let completions = self.completions.read();
1520 let filter_start = completions[mat.candidate_id].label.filter_range.start;
1521 for position in &mut mat.positions {
1522 *position += filter_start;
1523 }
1524 }
1525
1526 self.matches = matches.into();
1527 self.selected_item = 0;
1528 }
1529}
1530
1531#[derive(Clone)]
1532struct CodeActionsMenu {
1533 actions: Arc<[CodeAction]>,
1534 buffer: Model<Buffer>,
1535 selected_item: usize,
1536 list: UniformListState,
1537 deployed_from_indicator: bool,
1538}
1539
1540impl CodeActionsMenu {
1541 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1542 self.selected_item = 0;
1543 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1544 cx.notify()
1545 }
1546
1547 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1548 if self.selected_item > 0 {
1549 self.selected_item -= 1;
1550 } else {
1551 self.selected_item = self.actions.len() - 1;
1552 }
1553 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1554 cx.notify();
1555 }
1556
1557 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1558 if self.selected_item + 1 < self.actions.len() {
1559 self.selected_item += 1;
1560 } else {
1561 self.selected_item = 0;
1562 }
1563 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1564 cx.notify();
1565 }
1566
1567 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1568 self.selected_item = self.actions.len() - 1;
1569 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1570 cx.notify()
1571 }
1572
1573 fn visible(&self) -> bool {
1574 !self.actions.is_empty()
1575 }
1576
1577 fn render(
1578 &self,
1579 mut cursor_position: DisplayPoint,
1580 style: EditorStyle,
1581 cx: &mut ViewContext<Editor>,
1582 ) -> (DisplayPoint, AnyElement<Editor>) {
1583 todo!("old version below")
1584 }
1585 // enum ActionTag {}
1586
1587 // let container_style = style.autocomplete.container;
1588 // let actions = self.actions.clone();
1589 // let selected_item = self.selected_item;
1590 // let element = UniformList::new(
1591 // self.list.clone(),
1592 // actions.len(),
1593 // cx,
1594 // move |_, range, items, cx| {
1595 // let start_ix = range.start;
1596 // for (ix, action) in actions[range].iter().enumerate() {
1597 // let item_ix = start_ix + ix;
1598 // items.push(
1599 // MouseEventHandler::new::<ActionTag, _>(item_ix, cx, |state, _| {
1600 // let item_style = if item_ix == selected_item {
1601 // style.autocomplete.selected_item
1602 // } else if state.hovered() {
1603 // style.autocomplete.hovered_item
1604 // } else {
1605 // style.autocomplete.item
1606 // };
1607
1608 // Text::new(action.lsp_action.title.clone(), style.text.clone())
1609 // .with_soft_wrap(false)
1610 // .contained()
1611 // .with_style(item_style)
1612 // })
1613 // .with_cursor_style(CursorStyle::PointingHand)
1614 // .on_down(MouseButton::Left, move |_, this, cx| {
1615 // let workspace = this
1616 // .workspace
1617 // .as_ref()
1618 // .and_then(|(workspace, _)| workspace.upgrade(cx));
1619 // cx.window_context().defer(move |cx| {
1620 // if let Some(workspace) = workspace {
1621 // workspace.update(cx, |workspace, cx| {
1622 // if let Some(task) = Editor::confirm_code_action(
1623 // workspace,
1624 // &ConfirmCodeAction {
1625 // item_ix: Some(item_ix),
1626 // },
1627 // cx,
1628 // ) {
1629 // task.detach_and_log_err(cx);
1630 // }
1631 // });
1632 // }
1633 // });
1634 // })
1635 // .into_any(),
1636 // );
1637 // }
1638 // },
1639 // )
1640 // .with_width_from_item(
1641 // self.actions
1642 // .iter()
1643 // .enumerate()
1644 // .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
1645 // .map(|(ix, _)| ix),
1646 // )
1647 // .contained()
1648 // .with_style(container_style)
1649 // .into_any();
1650
1651 // if self.deployed_from_indicator {
1652 // *cursor_position.column_mut() = 0;
1653 // }
1654
1655 // (cursor_position, element)
1656 // }
1657}
1658
1659pub struct CopilotState {
1660 excerpt_id: Option<ExcerptId>,
1661 pending_refresh: Task<Option<()>>,
1662 pending_cycling_refresh: Task<Option<()>>,
1663 cycled: bool,
1664 completions: Vec<copilot::Completion>,
1665 active_completion_index: usize,
1666 suggestion: Option<Inlay>,
1667}
1668
1669impl Default for CopilotState {
1670 fn default() -> Self {
1671 Self {
1672 excerpt_id: None,
1673 pending_cycling_refresh: Task::ready(Some(())),
1674 pending_refresh: Task::ready(Some(())),
1675 completions: Default::default(),
1676 active_completion_index: 0,
1677 cycled: false,
1678 suggestion: None,
1679 }
1680 }
1681}
1682
1683impl CopilotState {
1684 fn active_completion(&self) -> Option<&copilot::Completion> {
1685 self.completions.get(self.active_completion_index)
1686 }
1687
1688 fn text_for_active_completion(
1689 &self,
1690 cursor: Anchor,
1691 buffer: &MultiBufferSnapshot,
1692 ) -> Option<&str> {
1693 use language::ToOffset as _;
1694
1695 let completion = self.active_completion()?;
1696 let excerpt_id = self.excerpt_id?;
1697 let completion_buffer = buffer.buffer_for_excerpt(excerpt_id)?;
1698 if excerpt_id != cursor.excerpt_id
1699 || !completion.range.start.is_valid(completion_buffer)
1700 || !completion.range.end.is_valid(completion_buffer)
1701 {
1702 return None;
1703 }
1704
1705 let mut completion_range = completion.range.to_offset(&completion_buffer);
1706 let prefix_len = Self::common_prefix(
1707 completion_buffer.chars_for_range(completion_range.clone()),
1708 completion.text.chars(),
1709 );
1710 completion_range.start += prefix_len;
1711 let suffix_len = Self::common_prefix(
1712 completion_buffer.reversed_chars_for_range(completion_range.clone()),
1713 completion.text[prefix_len..].chars().rev(),
1714 );
1715 completion_range.end = completion_range.end.saturating_sub(suffix_len);
1716
1717 if completion_range.is_empty()
1718 && completion_range.start == cursor.text_anchor.to_offset(&completion_buffer)
1719 {
1720 Some(&completion.text[prefix_len..completion.text.len() - suffix_len])
1721 } else {
1722 None
1723 }
1724 }
1725
1726 fn cycle_completions(&mut self, direction: Direction) {
1727 match direction {
1728 Direction::Prev => {
1729 self.active_completion_index = if self.active_completion_index == 0 {
1730 self.completions.len().saturating_sub(1)
1731 } else {
1732 self.active_completion_index - 1
1733 };
1734 }
1735 Direction::Next => {
1736 if self.completions.len() == 0 {
1737 self.active_completion_index = 0
1738 } else {
1739 self.active_completion_index =
1740 (self.active_completion_index + 1) % self.completions.len();
1741 }
1742 }
1743 }
1744 }
1745
1746 fn push_completion(&mut self, new_completion: copilot::Completion) {
1747 for completion in &self.completions {
1748 if completion.text == new_completion.text && completion.range == new_completion.range {
1749 return;
1750 }
1751 }
1752 self.completions.push(new_completion);
1753 }
1754
1755 fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1756 a.zip(b)
1757 .take_while(|(a, b)| a == b)
1758 .map(|(a, _)| a.len_utf8())
1759 .sum()
1760 }
1761}
1762
1763#[derive(Debug)]
1764struct ActiveDiagnosticGroup {
1765 primary_range: Range<Anchor>,
1766 primary_message: String,
1767 blocks: HashMap<BlockId, Diagnostic>,
1768 is_valid: bool,
1769}
1770
1771#[derive(Serialize, Deserialize)]
1772pub struct ClipboardSelection {
1773 pub len: usize,
1774 pub is_entire_line: bool,
1775 pub first_line_indent: u32,
1776}
1777
1778#[derive(Debug)]
1779pub struct NavigationData {
1780 cursor_anchor: Anchor,
1781 cursor_position: Point,
1782 scroll_anchor: ScrollAnchor,
1783 scroll_top_row: u32,
1784}
1785
1786pub struct EditorCreated(pub View<Editor>);
1787
1788enum GotoDefinitionKind {
1789 Symbol,
1790 Type,
1791}
1792
1793#[derive(Debug, Clone)]
1794enum InlayHintRefreshReason {
1795 Toggle(bool),
1796 SettingsChange(InlayHintSettings),
1797 NewLinesShown,
1798 BufferEdited(HashSet<Arc<Language>>),
1799 RefreshRequested,
1800 ExcerptsRemoved(Vec<ExcerptId>),
1801}
1802impl InlayHintRefreshReason {
1803 fn description(&self) -> &'static str {
1804 match self {
1805 Self::Toggle(_) => "toggle",
1806 Self::SettingsChange(_) => "settings change",
1807 Self::NewLinesShown => "new lines shown",
1808 Self::BufferEdited(_) => "buffer edited",
1809 Self::RefreshRequested => "refresh requested",
1810 Self::ExcerptsRemoved(_) => "excerpts removed",
1811 }
1812 }
1813}
1814
1815impl Editor {
1816 // pub fn single_line(
1817 // field_editor_style: Option<Arc<GetFieldEditorTheme>>,
1818 // cx: &mut ViewContext<Self>,
1819 // ) -> Self {
1820 // let buffer = cx.build_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
1821 // let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
1822 // Self::new(EditorMode::SingleLine, buffer, None, field_editor_style, cx)
1823 // }
1824
1825 // pub fn multi_line(
1826 // field_editor_style: Option<Arc<GetFieldEditorTheme>>,
1827 // cx: &mut ViewContext<Self>,
1828 // ) -> Self {
1829 // let buffer = cx.build_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
1830 // let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
1831 // Self::new(EditorMode::Full, buffer, None, field_editor_style, cx)
1832 // }
1833
1834 // pub fn auto_height(
1835 // max_lines: usize,
1836 // field_editor_style: Option<Arc<GetFieldEditorTheme>>,
1837 // cx: &mut ViewContext<Self>,
1838 // ) -> Self {
1839 // let buffer = cx.build_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
1840 // let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
1841 // Self::new(
1842 // EditorMode::AutoHeight { max_lines },
1843 // buffer,
1844 // None,
1845 // field_editor_style,
1846 // cx,
1847 // )
1848 // }
1849
1850 pub fn for_buffer(
1851 buffer: Model<Buffer>,
1852 project: Option<Model<Project>>,
1853 cx: &mut ViewContext<Self>,
1854 ) -> Self {
1855 let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
1856 Self::new(EditorMode::Full, buffer, project, cx)
1857 }
1858
1859 pub fn for_multibuffer(
1860 buffer: Model<MultiBuffer>,
1861 project: Option<Model<Project>>,
1862 cx: &mut ViewContext<Self>,
1863 ) -> Self {
1864 Self::new(EditorMode::Full, buffer, project, cx)
1865 }
1866
1867 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1868 let mut clone = Self::new(
1869 self.mode,
1870 self.buffer.clone(),
1871 self.project.clone(),
1872 // todo!
1873 // self.get_field_editor_theme.clone(),
1874 cx,
1875 );
1876 self.display_map.update(cx, |display_map, cx| {
1877 let snapshot = display_map.snapshot(cx);
1878 clone.display_map.update(cx, |display_map, cx| {
1879 display_map.set_state(&snapshot, cx);
1880 });
1881 });
1882 clone.selections.clone_state(&self.selections);
1883 clone.scroll_manager.clone_state(&self.scroll_manager);
1884 clone.searchable = self.searchable;
1885 clone
1886 }
1887
1888 fn new(
1889 mode: EditorMode,
1890 buffer: Model<MultiBuffer>,
1891 project: Option<Model<Project>>,
1892 // todo!()
1893 // get_field_editor_theme: Option<Arc<GetFieldEditorTheme>>,
1894 cx: &mut ViewContext<Self>,
1895 ) -> Self {
1896 // let editor_view_id = cx.view_id();
1897 let style = cx.text_style();
1898 let font_size = style.font_size.to_pixels(cx.rem_size());
1899 let display_map = cx.build_model(|cx| {
1900 // todo!()
1901 // let settings = settings::get::<ThemeSettings>(cx);
1902 // let style = build_style(settings, get_field_editor_theme.as_deref(), None, cx);
1903 DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
1904 });
1905
1906 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1907
1908 let blink_manager = cx.build_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1909
1910 let soft_wrap_mode_override =
1911 (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
1912
1913 let mut project_subscriptions = Vec::new();
1914 if mode == EditorMode::Full {
1915 if let Some(project) = project.as_ref() {
1916 if buffer.read(cx).is_singleton() {
1917 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1918 cx.emit(Event::TitleChanged);
1919 }));
1920 }
1921 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1922 if let project::Event::RefreshInlayHints = event {
1923 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1924 };
1925 }));
1926 }
1927 }
1928
1929 let inlay_hint_settings = inlay_hint_settings(
1930 selections.newest_anchor().head(),
1931 &buffer.read(cx).snapshot(cx),
1932 cx,
1933 );
1934
1935 let mut this = Self {
1936 handle: cx.view().downgrade(),
1937 focus_handle: cx.focus_handle(),
1938 buffer: buffer.clone(),
1939 display_map: display_map.clone(),
1940 selections,
1941 scroll_manager: ScrollManager::new(),
1942 columnar_selection_tail: None,
1943 add_selections_state: None,
1944 select_next_state: None,
1945 select_prev_state: None,
1946 selection_history: Default::default(),
1947 autoclose_regions: Default::default(),
1948 snippet_stack: Default::default(),
1949 select_larger_syntax_node_stack: Vec::new(),
1950 ime_transaction: Default::default(),
1951 active_diagnostics: None,
1952 soft_wrap_mode_override,
1953 // get_field_editor_theme,
1954 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1955 project,
1956 blink_manager: blink_manager.clone(),
1957 show_local_selections: true,
1958 mode,
1959 show_gutter: mode == EditorMode::Full,
1960 show_wrap_guides: None,
1961 placeholder_text: None,
1962 highlighted_rows: None,
1963 background_highlights: Default::default(),
1964 inlay_background_highlights: Default::default(),
1965 nav_history: None,
1966 context_menu: RwLock::new(None),
1967 // mouse_context_menu: cx
1968 // .add_view(|cx| context_menu::ContextMenu::new(editor_view_id, cx)),
1969 completion_tasks: Default::default(),
1970 next_completion_id: 0,
1971 next_inlay_id: 0,
1972 available_code_actions: Default::default(),
1973 code_actions_task: Default::default(),
1974 document_highlights_task: Default::default(),
1975 pending_rename: Default::default(),
1976 searchable: true,
1977 // override_text_style: None,
1978 cursor_shape: Default::default(),
1979 autoindent_mode: Some(AutoindentMode::EachLine),
1980 collapse_matches: false,
1981 workspace: None,
1982 keymap_context_layers: Default::default(),
1983 input_enabled: true,
1984 read_only: false,
1985 leader_peer_id: None,
1986 remote_id: None,
1987 hover_state: Default::default(),
1988 link_go_to_definition_state: Default::default(),
1989 copilot_state: Default::default(),
1990 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1991 gutter_hovered: false,
1992 pixel_position_of_newest_cursor: None,
1993 style: None,
1994 _subscriptions: vec![
1995 cx.observe(&buffer, Self::on_buffer_changed),
1996 cx.subscribe(&buffer, Self::on_buffer_event),
1997 cx.observe(&display_map, Self::on_display_map_changed),
1998 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1999 cx.observe_global::<SettingsStore>(Self::settings_changed),
2000 cx.observe_window_activation(|editor, cx| {
2001 let active = cx.is_window_active();
2002 editor.blink_manager.update(cx, |blink_manager, cx| {
2003 if active {
2004 blink_manager.enable(cx);
2005 } else {
2006 blink_manager.show_cursor(cx);
2007 blink_manager.disable(cx);
2008 }
2009 });
2010 }),
2011 ],
2012 };
2013
2014 this._subscriptions.extend(project_subscriptions);
2015
2016 this.end_selection(cx);
2017 this.scroll_manager.show_scrollbar(cx);
2018
2019 // todo!("use a different mechanism")
2020 // let editor_created_event = EditorCreated(cx.handle());
2021 // cx.emit_global(editor_created_event);
2022
2023 if mode == EditorMode::Full {
2024 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2025 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2026 }
2027
2028 this.report_editor_event("open", None, cx);
2029 this
2030 }
2031
2032 fn dispatch_context(&self, cx: &AppContext) -> DispatchContext {
2033 let mut dispatch_context = DispatchContext::default();
2034 dispatch_context.insert("Editor");
2035 let mode = match self.mode {
2036 EditorMode::SingleLine => "single_line",
2037 EditorMode::AutoHeight { .. } => "auto_height",
2038 EditorMode::Full => "full",
2039 };
2040 dispatch_context.set("mode", mode);
2041 if self.pending_rename.is_some() {
2042 dispatch_context.insert("renaming");
2043 }
2044 if self.context_menu_visible() {
2045 match self.context_menu.read().as_ref() {
2046 Some(ContextMenu::Completions(_)) => {
2047 dispatch_context.insert("menu");
2048 dispatch_context.insert("showing_completions")
2049 }
2050 Some(ContextMenu::CodeActions(_)) => {
2051 dispatch_context.insert("menu");
2052 dispatch_context.insert("showing_code_actions")
2053 }
2054 None => {}
2055 }
2056 }
2057
2058 for layer in self.keymap_context_layers.values() {
2059 dispatch_context.extend(layer);
2060 }
2061
2062 if let Some(extension) = self
2063 .buffer
2064 .read(cx)
2065 .as_singleton()
2066 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2067 {
2068 dispatch_context.set("extension", extension.to_string());
2069 }
2070
2071 dispatch_context
2072 }
2073
2074 // pub fn new_file(
2075 // workspace: &mut Workspace,
2076 // _: &workspace::NewFile,
2077 // cx: &mut ViewContext<Workspace>,
2078 // ) {
2079 // let project = workspace.project().clone();
2080 // if project.read(cx).is_remote() {
2081 // cx.propagate();
2082 // } else if let Some(buffer) = project
2083 // .update(cx, |project, cx| project.create_buffer("", None, cx))
2084 // .log_err()
2085 // {
2086 // workspace.add_item(
2087 // Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
2088 // cx,
2089 // );
2090 // }
2091 // }
2092
2093 // pub fn new_file_in_direction(
2094 // workspace: &mut Workspace,
2095 // action: &workspace::NewFileInDirection,
2096 // cx: &mut ViewContext<Workspace>,
2097 // ) {
2098 // let project = workspace.project().clone();
2099 // if project.read(cx).is_remote() {
2100 // cx.propagate();
2101 // } else if let Some(buffer) = project
2102 // .update(cx, |project, cx| project.create_buffer("", None, cx))
2103 // .log_err()
2104 // {
2105 // workspace.split_item(
2106 // action.0,
2107 // Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
2108 // cx,
2109 // );
2110 // }
2111 // }
2112
2113 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2114 self.buffer.read(cx).replica_id()
2115 }
2116
2117 // pub fn leader_peer_id(&self) -> Option<PeerId> {
2118 // self.leader_peer_id
2119 // }
2120
2121 pub fn buffer(&self) -> &Model<MultiBuffer> {
2122 &self.buffer
2123 }
2124
2125 fn workspace(&self) -> Option<View<Workspace>> {
2126 self.workspace.as_ref()?.0.upgrade()
2127 }
2128
2129 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2130 self.buffer().read(cx).title(cx)
2131 }
2132
2133 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2134 EditorSnapshot {
2135 mode: self.mode,
2136 show_gutter: self.show_gutter,
2137 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2138 scroll_anchor: self.scroll_manager.anchor(),
2139 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2140 placeholder_text: self.placeholder_text.clone(),
2141 is_focused: self.focus_handle.is_focused(cx),
2142 }
2143 }
2144
2145 // pub fn language_at<'a, T: ToOffset>(
2146 // &self,
2147 // point: T,
2148 // cx: &'a AppContext,
2149 // ) -> Option<Arc<Language>> {
2150 // self.buffer.read(cx).language_at(point, cx)
2151 // }
2152
2153 // pub fn file_at<'a, T: ToOffset>(&self, point: T, cx: &'a AppContext) -> Option<Arc<dyn File>> {
2154 // self.buffer.read(cx).read(cx).file_at(point).cloned()
2155 // }
2156
2157 // pub fn active_excerpt(
2158 // &self,
2159 // cx: &AppContext,
2160 // ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2161 // self.buffer
2162 // .read(cx)
2163 // .excerpt_containing(self.selections.newest_anchor().head(), cx)
2164 // }
2165
2166 // pub fn style(&self, cx: &AppContext) -> EditorStyle {
2167 // build_style(
2168 // settings::get::<ThemeSettings>(cx),
2169 // self.get_field_editor_theme.as_deref(),
2170 // self.override_text_style.as_deref(),
2171 // cx,
2172 // )
2173 // }
2174
2175 // pub fn mode(&self) -> EditorMode {
2176 // self.mode
2177 // }
2178
2179 // pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2180 // self.collaboration_hub.as_deref()
2181 // }
2182
2183 // pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2184 // self.collaboration_hub = Some(hub);
2185 // }
2186
2187 // pub fn set_placeholder_text(
2188 // &mut self,
2189 // placeholder_text: impl Into<Arc<str>>,
2190 // cx: &mut ViewContext<Self>,
2191 // ) {
2192 // self.placeholder_text = Some(placeholder_text.into());
2193 // cx.notify();
2194 // }
2195
2196 // pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2197 // self.cursor_shape = cursor_shape;
2198 // cx.notify();
2199 // }
2200
2201 // pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2202 // self.collapse_matches = collapse_matches;
2203 // }
2204
2205 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2206 if self.collapse_matches {
2207 return range.start..range.start;
2208 }
2209 range.clone()
2210 }
2211
2212 // pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2213 // if self.display_map.read(cx).clip_at_line_ends != clip {
2214 // self.display_map
2215 // .update(cx, |map, _| map.clip_at_line_ends = clip);
2216 // }
2217 // }
2218
2219 // pub fn set_keymap_context_layer<Tag: 'static>(
2220 // &mut self,
2221 // context: KeymapContext,
2222 // cx: &mut ViewContext<Self>,
2223 // ) {
2224 // self.keymap_context_layers
2225 // .insert(TypeId::of::<Tag>(), context);
2226 // cx.notify();
2227 // }
2228
2229 // pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2230 // self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2231 // cx.notify();
2232 // }
2233
2234 // pub fn set_input_enabled(&mut self, input_enabled: bool) {
2235 // self.input_enabled = input_enabled;
2236 // }
2237
2238 // pub fn set_autoindent(&mut self, autoindent: bool) {
2239 // if autoindent {
2240 // self.autoindent_mode = Some(AutoindentMode::EachLine);
2241 // } else {
2242 // self.autoindent_mode = None;
2243 // }
2244 // }
2245
2246 // pub fn read_only(&self) -> bool {
2247 // self.read_only
2248 // }
2249
2250 // pub fn set_read_only(&mut self, read_only: bool) {
2251 // self.read_only = read_only;
2252 // }
2253
2254 // pub fn set_field_editor_style(
2255 // &mut self,
2256 // style: Option<Arc<GetFieldEditorTheme>>,
2257 // cx: &mut ViewContext<Self>,
2258 // ) {
2259 // self.get_field_editor_theme = style;
2260 // cx.notify();
2261 // }
2262
2263 fn selections_did_change(
2264 &mut self,
2265 local: bool,
2266 old_cursor_position: &Anchor,
2267 cx: &mut ViewContext<Self>,
2268 ) {
2269 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2270 self.buffer.update(cx, |buffer, cx| {
2271 buffer.set_active_selections(
2272 &self.selections.disjoint_anchors(),
2273 self.selections.line_mode,
2274 self.cursor_shape,
2275 cx,
2276 )
2277 });
2278 }
2279
2280 let display_map = self
2281 .display_map
2282 .update(cx, |display_map, cx| display_map.snapshot(cx));
2283 let buffer = &display_map.buffer_snapshot;
2284 self.add_selections_state = None;
2285 self.select_next_state = None;
2286 self.select_prev_state = None;
2287 self.select_larger_syntax_node_stack.clear();
2288 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2289 self.snippet_stack
2290 .invalidate(&self.selections.disjoint_anchors(), buffer);
2291 self.take_rename(false, cx);
2292
2293 let new_cursor_position = self.selections.newest_anchor().head();
2294
2295 self.push_to_nav_history(
2296 old_cursor_position.clone(),
2297 Some(new_cursor_position.to_point(buffer)),
2298 cx,
2299 );
2300
2301 if local {
2302 let new_cursor_position = self.selections.newest_anchor().head();
2303 let mut context_menu = self.context_menu.write();
2304 let completion_menu = match context_menu.as_ref() {
2305 Some(ContextMenu::Completions(menu)) => Some(menu),
2306
2307 _ => {
2308 *context_menu = None;
2309 None
2310 }
2311 };
2312
2313 if let Some(completion_menu) = completion_menu {
2314 let cursor_position = new_cursor_position.to_offset(buffer);
2315 let (word_range, kind) =
2316 buffer.surrounding_word(completion_menu.initial_position.clone());
2317 if kind == Some(CharKind::Word)
2318 && word_range.to_inclusive().contains(&cursor_position)
2319 {
2320 let mut completion_menu = completion_menu.clone();
2321 drop(context_menu);
2322
2323 let query = Self::completion_query(buffer, cursor_position);
2324 cx.spawn(move |this, mut cx| async move {
2325 completion_menu
2326 .filter(query.as_deref(), cx.background_executor().clone())
2327 .await;
2328
2329 this.update(&mut cx, |this, cx| {
2330 let mut context_menu = this.context_menu.write();
2331 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2332 return;
2333 };
2334
2335 if menu.id > completion_menu.id {
2336 return;
2337 }
2338
2339 *context_menu = Some(ContextMenu::Completions(completion_menu));
2340 drop(context_menu);
2341 cx.notify();
2342 })
2343 })
2344 .detach();
2345
2346 self.show_completions(&ShowCompletions, cx);
2347 } else {
2348 drop(context_menu);
2349 self.hide_context_menu(cx);
2350 }
2351 } else {
2352 drop(context_menu);
2353 }
2354
2355 hide_hover(self, cx);
2356
2357 if old_cursor_position.to_display_point(&display_map).row()
2358 != new_cursor_position.to_display_point(&display_map).row()
2359 {
2360 self.available_code_actions.take();
2361 }
2362 self.refresh_code_actions(cx);
2363 self.refresh_document_highlights(cx);
2364 refresh_matching_bracket_highlights(self, cx);
2365 self.discard_copilot_suggestion(cx);
2366 }
2367
2368 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2369 cx.emit(Event::SelectionsChanged { local });
2370 cx.notify();
2371 }
2372
2373 pub fn change_selections<R>(
2374 &mut self,
2375 autoscroll: Option<Autoscroll>,
2376 cx: &mut ViewContext<Self>,
2377 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2378 ) -> R {
2379 let old_cursor_position = self.selections.newest_anchor().head();
2380 self.push_to_selection_history();
2381
2382 let (changed, result) = self.selections.change_with(cx, change);
2383
2384 if changed {
2385 if let Some(autoscroll) = autoscroll {
2386 self.request_autoscroll(autoscroll, cx);
2387 }
2388 self.selections_did_change(true, &old_cursor_position, cx);
2389 }
2390
2391 result
2392 }
2393
2394 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2395 where
2396 I: IntoIterator<Item = (Range<S>, T)>,
2397 S: ToOffset,
2398 T: Into<Arc<str>>,
2399 {
2400 if self.read_only {
2401 return;
2402 }
2403
2404 self.buffer
2405 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2406 }
2407
2408 // pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2409 // where
2410 // I: IntoIterator<Item = (Range<S>, T)>,
2411 // S: ToOffset,
2412 // T: Into<Arc<str>>,
2413 // {
2414 // if self.read_only {
2415 // return;
2416 // }
2417
2418 // self.buffer.update(cx, |buffer, cx| {
2419 // buffer.edit(edits, self.autoindent_mode.clone(), cx)
2420 // });
2421 // }
2422
2423 // pub fn edit_with_block_indent<I, S, T>(
2424 // &mut self,
2425 // edits: I,
2426 // original_indent_columns: Vec<u32>,
2427 // cx: &mut ViewContext<Self>,
2428 // ) where
2429 // I: IntoIterator<Item = (Range<S>, T)>,
2430 // S: ToOffset,
2431 // T: Into<Arc<str>>,
2432 // {
2433 // if self.read_only {
2434 // return;
2435 // }
2436
2437 // self.buffer.update(cx, |buffer, cx| {
2438 // buffer.edit(
2439 // edits,
2440 // Some(AutoindentMode::Block {
2441 // original_indent_columns,
2442 // }),
2443 // cx,
2444 // )
2445 // });
2446 // }
2447
2448 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2449 self.hide_context_menu(cx);
2450
2451 match phase {
2452 SelectPhase::Begin {
2453 position,
2454 add,
2455 click_count,
2456 } => self.begin_selection(position, add, click_count, cx),
2457 SelectPhase::BeginColumnar {
2458 position,
2459 goal_column,
2460 } => self.begin_columnar_selection(position, goal_column, cx),
2461 SelectPhase::Extend {
2462 position,
2463 click_count,
2464 } => self.extend_selection(position, click_count, cx),
2465 SelectPhase::Update {
2466 position,
2467 goal_column,
2468 scroll_position,
2469 } => self.update_selection(position, goal_column, scroll_position, cx),
2470 SelectPhase::End => self.end_selection(cx),
2471 }
2472 }
2473
2474 fn extend_selection(
2475 &mut self,
2476 position: DisplayPoint,
2477 click_count: usize,
2478 cx: &mut ViewContext<Self>,
2479 ) {
2480 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2481 let tail = self.selections.newest::<usize>(cx).tail();
2482 self.begin_selection(position, false, click_count, cx);
2483
2484 let position = position.to_offset(&display_map, Bias::Left);
2485 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2486
2487 let mut pending_selection = self
2488 .selections
2489 .pending_anchor()
2490 .expect("extend_selection not called with pending selection");
2491 if position >= tail {
2492 pending_selection.start = tail_anchor;
2493 } else {
2494 pending_selection.end = tail_anchor;
2495 pending_selection.reversed = true;
2496 }
2497
2498 let mut pending_mode = self.selections.pending_mode().unwrap();
2499 match &mut pending_mode {
2500 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2501 _ => {}
2502 }
2503
2504 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2505 s.set_pending(pending_selection, pending_mode)
2506 });
2507 }
2508
2509 fn begin_selection(
2510 &mut self,
2511 position: DisplayPoint,
2512 add: bool,
2513 click_count: usize,
2514 cx: &mut ViewContext<Self>,
2515 ) {
2516 if !self.focus_handle.is_focused(cx) {
2517 cx.focus(&self.focus_handle);
2518 }
2519
2520 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2521 let buffer = &display_map.buffer_snapshot;
2522 let newest_selection = self.selections.newest_anchor().clone();
2523 let position = display_map.clip_point(position, Bias::Left);
2524
2525 let start;
2526 let end;
2527 let mode;
2528 let auto_scroll;
2529 match click_count {
2530 1 => {
2531 start = buffer.anchor_before(position.to_point(&display_map));
2532 end = start.clone();
2533 mode = SelectMode::Character;
2534 auto_scroll = true;
2535 }
2536 2 => {
2537 let range = movement::surrounding_word(&display_map, position);
2538 start = buffer.anchor_before(range.start.to_point(&display_map));
2539 end = buffer.anchor_before(range.end.to_point(&display_map));
2540 mode = SelectMode::Word(start.clone()..end.clone());
2541 auto_scroll = true;
2542 }
2543 3 => {
2544 let position = display_map
2545 .clip_point(position, Bias::Left)
2546 .to_point(&display_map);
2547 let line_start = display_map.prev_line_boundary(position).0;
2548 let next_line_start = buffer.clip_point(
2549 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2550 Bias::Left,
2551 );
2552 start = buffer.anchor_before(line_start);
2553 end = buffer.anchor_before(next_line_start);
2554 mode = SelectMode::Line(start.clone()..end.clone());
2555 auto_scroll = true;
2556 }
2557 _ => {
2558 start = buffer.anchor_before(0);
2559 end = buffer.anchor_before(buffer.len());
2560 mode = SelectMode::All;
2561 auto_scroll = false;
2562 }
2563 }
2564
2565 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2566 if !add {
2567 s.clear_disjoint();
2568 } else if click_count > 1 {
2569 s.delete(newest_selection.id)
2570 }
2571
2572 s.set_pending_anchor_range(start..end, mode);
2573 });
2574 }
2575
2576 fn begin_columnar_selection(
2577 &mut self,
2578 position: DisplayPoint,
2579 goal_column: u32,
2580 cx: &mut ViewContext<Self>,
2581 ) {
2582 if !self.focus_handle.is_focused(cx) {
2583 cx.focus(&self.focus_handle);
2584 }
2585
2586 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2587 let tail = self.selections.newest::<Point>(cx).tail();
2588 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2589
2590 self.select_columns(
2591 tail.to_display_point(&display_map),
2592 position,
2593 goal_column,
2594 &display_map,
2595 cx,
2596 );
2597 }
2598
2599 fn update_selection(
2600 &mut self,
2601 position: DisplayPoint,
2602 goal_column: u32,
2603 scroll_position: gpui::Point<f32>,
2604 cx: &mut ViewContext<Self>,
2605 ) {
2606 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2607
2608 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2609 let tail = tail.to_display_point(&display_map);
2610 self.select_columns(tail, position, goal_column, &display_map, cx);
2611 } else if let Some(mut pending) = self.selections.pending_anchor() {
2612 let buffer = self.buffer.read(cx).snapshot(cx);
2613 let head;
2614 let tail;
2615 let mode = self.selections.pending_mode().unwrap();
2616 match &mode {
2617 SelectMode::Character => {
2618 head = position.to_point(&display_map);
2619 tail = pending.tail().to_point(&buffer);
2620 }
2621 SelectMode::Word(original_range) => {
2622 let original_display_range = original_range.start.to_display_point(&display_map)
2623 ..original_range.end.to_display_point(&display_map);
2624 let original_buffer_range = original_display_range.start.to_point(&display_map)
2625 ..original_display_range.end.to_point(&display_map);
2626 if movement::is_inside_word(&display_map, position)
2627 || original_display_range.contains(&position)
2628 {
2629 let word_range = movement::surrounding_word(&display_map, position);
2630 if word_range.start < original_display_range.start {
2631 head = word_range.start.to_point(&display_map);
2632 } else {
2633 head = word_range.end.to_point(&display_map);
2634 }
2635 } else {
2636 head = position.to_point(&display_map);
2637 }
2638
2639 if head <= original_buffer_range.start {
2640 tail = original_buffer_range.end;
2641 } else {
2642 tail = original_buffer_range.start;
2643 }
2644 }
2645 SelectMode::Line(original_range) => {
2646 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2647
2648 let position = display_map
2649 .clip_point(position, Bias::Left)
2650 .to_point(&display_map);
2651 let line_start = display_map.prev_line_boundary(position).0;
2652 let next_line_start = buffer.clip_point(
2653 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2654 Bias::Left,
2655 );
2656
2657 if line_start < original_range.start {
2658 head = line_start
2659 } else {
2660 head = next_line_start
2661 }
2662
2663 if head <= original_range.start {
2664 tail = original_range.end;
2665 } else {
2666 tail = original_range.start;
2667 }
2668 }
2669 SelectMode::All => {
2670 return;
2671 }
2672 };
2673
2674 if head < tail {
2675 pending.start = buffer.anchor_before(head);
2676 pending.end = buffer.anchor_before(tail);
2677 pending.reversed = true;
2678 } else {
2679 pending.start = buffer.anchor_before(tail);
2680 pending.end = buffer.anchor_before(head);
2681 pending.reversed = false;
2682 }
2683
2684 self.change_selections(None, cx, |s| {
2685 s.set_pending(pending, mode);
2686 });
2687 } else {
2688 log::error!("update_selection dispatched with no pending selection");
2689 return;
2690 }
2691
2692 self.set_scroll_position(scroll_position, cx);
2693 cx.notify();
2694 }
2695
2696 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2697 self.columnar_selection_tail.take();
2698 if self.selections.pending_anchor().is_some() {
2699 let selections = self.selections.all::<usize>(cx);
2700 self.change_selections(None, cx, |s| {
2701 s.select(selections);
2702 s.clear_pending();
2703 });
2704 }
2705 }
2706
2707 fn select_columns(
2708 &mut self,
2709 tail: DisplayPoint,
2710 head: DisplayPoint,
2711 goal_column: u32,
2712 display_map: &DisplaySnapshot,
2713 cx: &mut ViewContext<Self>,
2714 ) {
2715 let start_row = cmp::min(tail.row(), head.row());
2716 let end_row = cmp::max(tail.row(), head.row());
2717 let start_column = cmp::min(tail.column(), goal_column);
2718 let end_column = cmp::max(tail.column(), goal_column);
2719 let reversed = start_column < tail.column();
2720
2721 let selection_ranges = (start_row..=end_row)
2722 .filter_map(|row| {
2723 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2724 let start = display_map
2725 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2726 .to_point(display_map);
2727 let end = display_map
2728 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2729 .to_point(display_map);
2730 if reversed {
2731 Some(end..start)
2732 } else {
2733 Some(start..end)
2734 }
2735 } else {
2736 None
2737 }
2738 })
2739 .collect::<Vec<_>>();
2740
2741 self.change_selections(None, cx, |s| {
2742 s.select_ranges(selection_ranges);
2743 });
2744 cx.notify();
2745 }
2746
2747 pub fn has_pending_nonempty_selection(&self) -> bool {
2748 let pending_nonempty_selection = match self.selections.pending_anchor() {
2749 Some(Selection { start, end, .. }) => start != end,
2750 None => false,
2751 };
2752 pending_nonempty_selection || self.columnar_selection_tail.is_some()
2753 }
2754
2755 pub fn has_pending_selection(&self) -> bool {
2756 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2757 }
2758
2759 // pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2760 // if self.take_rename(false, cx).is_some() {
2761 // return;
2762 // }
2763
2764 // if hide_hover(self, cx) {
2765 // return;
2766 // }
2767
2768 // if self.hide_context_menu(cx).is_some() {
2769 // return;
2770 // }
2771
2772 // if self.discard_copilot_suggestion(cx) {
2773 // return;
2774 // }
2775
2776 // if self.snippet_stack.pop().is_some() {
2777 // return;
2778 // }
2779
2780 // if self.mode == EditorMode::Full {
2781 // if self.active_diagnostics.is_some() {
2782 // self.dismiss_diagnostics(cx);
2783 // return;
2784 // }
2785
2786 // if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2787 // return;
2788 // }
2789 // }
2790
2791 // cx.propagate();
2792 // }
2793
2794 // pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2795 // let text: Arc<str> = text.into();
2796
2797 // if self.read_only {
2798 // return;
2799 // }
2800
2801 // let selections = self.selections.all_adjusted(cx);
2802 // let mut brace_inserted = false;
2803 // let mut edits = Vec::new();
2804 // let mut new_selections = Vec::with_capacity(selections.len());
2805 // let mut new_autoclose_regions = Vec::new();
2806 // let snapshot = self.buffer.read(cx).read(cx);
2807
2808 // for (selection, autoclose_region) in
2809 // self.selections_with_autoclose_regions(selections, &snapshot)
2810 // {
2811 // if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2812 // // Determine if the inserted text matches the opening or closing
2813 // // bracket of any of this language's bracket pairs.
2814 // let mut bracket_pair = None;
2815 // let mut is_bracket_pair_start = false;
2816 // if !text.is_empty() {
2817 // // `text` can be empty when an user is using IME (e.g. Chinese Wubi Simplified)
2818 // // and they are removing the character that triggered IME popup.
2819 // for (pair, enabled) in scope.brackets() {
2820 // if enabled && pair.close && pair.start.ends_with(text.as_ref()) {
2821 // bracket_pair = Some(pair.clone());
2822 // is_bracket_pair_start = true;
2823 // break;
2824 // } else if pair.end.as_str() == text.as_ref() {
2825 // bracket_pair = Some(pair.clone());
2826 // break;
2827 // }
2828 // }
2829 // }
2830
2831 // if let Some(bracket_pair) = bracket_pair {
2832 // if selection.is_empty() {
2833 // if is_bracket_pair_start {
2834 // let prefix_len = bracket_pair.start.len() - text.len();
2835
2836 // // If the inserted text is a suffix of an opening bracket and the
2837 // // selection is preceded by the rest of the opening bracket, then
2838 // // insert the closing bracket.
2839 // let following_text_allows_autoclose = snapshot
2840 // .chars_at(selection.start)
2841 // .next()
2842 // .map_or(true, |c| scope.should_autoclose_before(c));
2843 // let preceding_text_matches_prefix = prefix_len == 0
2844 // || (selection.start.column >= (prefix_len as u32)
2845 // && snapshot.contains_str_at(
2846 // Point::new(
2847 // selection.start.row,
2848 // selection.start.column - (prefix_len as u32),
2849 // ),
2850 // &bracket_pair.start[..prefix_len],
2851 // ));
2852 // if following_text_allows_autoclose && preceding_text_matches_prefix {
2853 // let anchor = snapshot.anchor_before(selection.end);
2854 // new_selections.push((selection.map(|_| anchor), text.len()));
2855 // new_autoclose_regions.push((
2856 // anchor,
2857 // text.len(),
2858 // selection.id,
2859 // bracket_pair.clone(),
2860 // ));
2861 // edits.push((
2862 // selection.range(),
2863 // format!("{}{}", text, bracket_pair.end).into(),
2864 // ));
2865 // brace_inserted = true;
2866 // continue;
2867 // }
2868 // }
2869
2870 // if let Some(region) = autoclose_region {
2871 // // If the selection is followed by an auto-inserted closing bracket,
2872 // // then don't insert that closing bracket again; just move the selection
2873 // // past the closing bracket.
2874 // let should_skip = selection.end == region.range.end.to_point(&snapshot)
2875 // && text.as_ref() == region.pair.end.as_str();
2876 // if should_skip {
2877 // let anchor = snapshot.anchor_after(selection.end);
2878 // new_selections
2879 // .push((selection.map(|_| anchor), region.pair.end.len()));
2880 // continue;
2881 // }
2882 // }
2883 // }
2884 // // If an opening bracket is 1 character long and is typed while
2885 // // text is selected, then surround that text with the bracket pair.
2886 // else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2887 // edits.push((selection.start..selection.start, text.clone()));
2888 // edits.push((
2889 // selection.end..selection.end,
2890 // bracket_pair.end.as_str().into(),
2891 // ));
2892 // brace_inserted = true;
2893 // new_selections.push((
2894 // Selection {
2895 // id: selection.id,
2896 // start: snapshot.anchor_after(selection.start),
2897 // end: snapshot.anchor_before(selection.end),
2898 // reversed: selection.reversed,
2899 // goal: selection.goal,
2900 // },
2901 // 0,
2902 // ));
2903 // continue;
2904 // }
2905 // }
2906 // }
2907
2908 // // If not handling any auto-close operation, then just replace the selected
2909 // // text with the given input and move the selection to the end of the
2910 // // newly inserted text.
2911 // let anchor = snapshot.anchor_after(selection.end);
2912 // new_selections.push((selection.map(|_| anchor), 0));
2913 // edits.push((selection.start..selection.end, text.clone()));
2914 // }
2915
2916 // drop(snapshot);
2917 // self.transact(cx, |this, cx| {
2918 // this.buffer.update(cx, |buffer, cx| {
2919 // buffer.edit(edits, this.autoindent_mode.clone(), cx);
2920 // });
2921
2922 // let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2923 // let new_selection_deltas = new_selections.iter().map(|e| e.1);
2924 // let snapshot = this.buffer.read(cx).read(cx);
2925 // let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2926 // .zip(new_selection_deltas)
2927 // .map(|(selection, delta)| Selection {
2928 // id: selection.id,
2929 // start: selection.start + delta,
2930 // end: selection.end + delta,
2931 // reversed: selection.reversed,
2932 // goal: SelectionGoal::None,
2933 // })
2934 // .collect::<Vec<_>>();
2935
2936 // let mut i = 0;
2937 // for (position, delta, selection_id, pair) in new_autoclose_regions {
2938 // let position = position.to_offset(&snapshot) + delta;
2939 // let start = snapshot.anchor_before(position);
2940 // let end = snapshot.anchor_after(position);
2941 // while let Some(existing_state) = this.autoclose_regions.get(i) {
2942 // match existing_state.range.start.cmp(&start, &snapshot) {
2943 // Ordering::Less => i += 1,
2944 // Ordering::Greater => break,
2945 // Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2946 // Ordering::Less => i += 1,
2947 // Ordering::Equal => break,
2948 // Ordering::Greater => break,
2949 // },
2950 // }
2951 // }
2952 // this.autoclose_regions.insert(
2953 // i,
2954 // AutocloseRegion {
2955 // selection_id,
2956 // range: start..end,
2957 // pair,
2958 // },
2959 // );
2960 // }
2961
2962 // drop(snapshot);
2963 // let had_active_copilot_suggestion = this.has_active_copilot_suggestion(cx);
2964 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2965
2966 // if !brace_inserted && EditorSettings>(cx).use_on_type_format {
2967 // if let Some(on_type_format_task) =
2968 // this.trigger_on_type_formatting(text.to_string(), cx)
2969 // {
2970 // on_type_format_task.detach_and_log_err(cx);
2971 // }
2972 // }
2973
2974 // if had_active_copilot_suggestion {
2975 // this.refresh_copilot_suggestions(true, cx);
2976 // if !this.has_active_copilot_suggestion(cx) {
2977 // this.trigger_completion_on_input(&text, cx);
2978 // }
2979 // } else {
2980 // this.trigger_completion_on_input(&text, cx);
2981 // this.refresh_copilot_suggestions(true, cx);
2982 // }
2983 // });
2984 // }
2985
2986 // pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2987 // self.transact(cx, |this, cx| {
2988 // let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2989 // let selections = this.selections.all::<usize>(cx);
2990 // let multi_buffer = this.buffer.read(cx);
2991 // let buffer = multi_buffer.snapshot(cx);
2992 // selections
2993 // .iter()
2994 // .map(|selection| {
2995 // let start_point = selection.start.to_point(&buffer);
2996 // let mut indent = buffer.indent_size_for_line(start_point.row);
2997 // indent.len = cmp::min(indent.len, start_point.column);
2998 // let start = selection.start;
2999 // let end = selection.end;
3000 // let is_cursor = start == end;
3001 // let language_scope = buffer.language_scope_at(start);
3002 // let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3003 // &language_scope
3004 // {
3005 // let leading_whitespace_len = buffer
3006 // .reversed_chars_at(start)
3007 // .take_while(|c| c.is_whitespace() && *c != '\n')
3008 // .map(|c| c.len_utf8())
3009 // .sum::<usize>();
3010
3011 // let trailing_whitespace_len = buffer
3012 // .chars_at(end)
3013 // .take_while(|c| c.is_whitespace() && *c != '\n')
3014 // .map(|c| c.len_utf8())
3015 // .sum::<usize>();
3016
3017 // let insert_extra_newline =
3018 // language.brackets().any(|(pair, enabled)| {
3019 // let pair_start = pair.start.trim_end();
3020 // let pair_end = pair.end.trim_start();
3021
3022 // enabled
3023 // && pair.newline
3024 // && buffer.contains_str_at(
3025 // end + trailing_whitespace_len,
3026 // pair_end,
3027 // )
3028 // && buffer.contains_str_at(
3029 // (start - leading_whitespace_len)
3030 // .saturating_sub(pair_start.len()),
3031 // pair_start,
3032 // )
3033 // });
3034 // // Comment extension on newline is allowed only for cursor selections
3035 // let comment_delimiter = language.line_comment_prefix().filter(|_| {
3036 // let is_comment_extension_enabled =
3037 // multi_buffer.settings_at(0, cx).extend_comment_on_newline;
3038 // is_cursor && is_comment_extension_enabled
3039 // });
3040 // let comment_delimiter = if let Some(delimiter) = comment_delimiter {
3041 // buffer
3042 // .buffer_line_for_row(start_point.row)
3043 // .is_some_and(|(snapshot, range)| {
3044 // let mut index_of_first_non_whitespace = 0;
3045 // let line_starts_with_comment = snapshot
3046 // .chars_for_range(range)
3047 // .skip_while(|c| {
3048 // let should_skip = c.is_whitespace();
3049 // if should_skip {
3050 // index_of_first_non_whitespace += 1;
3051 // }
3052 // should_skip
3053 // })
3054 // .take(delimiter.len())
3055 // .eq(delimiter.chars());
3056 // let cursor_is_placed_after_comment_marker =
3057 // index_of_first_non_whitespace + delimiter.len()
3058 // <= start_point.column as usize;
3059 // line_starts_with_comment
3060 // && cursor_is_placed_after_comment_marker
3061 // })
3062 // .then(|| delimiter.clone())
3063 // } else {
3064 // None
3065 // };
3066 // (comment_delimiter, insert_extra_newline)
3067 // } else {
3068 // (None, false)
3069 // };
3070
3071 // let capacity_for_delimiter = comment_delimiter
3072 // .as_deref()
3073 // .map(str::len)
3074 // .unwrap_or_default();
3075 // let mut new_text =
3076 // String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3077 // new_text.push_str("\n");
3078 // new_text.extend(indent.chars());
3079 // if let Some(delimiter) = &comment_delimiter {
3080 // new_text.push_str(&delimiter);
3081 // }
3082 // if insert_extra_newline {
3083 // new_text = new_text.repeat(2);
3084 // }
3085
3086 // let anchor = buffer.anchor_after(end);
3087 // let new_selection = selection.map(|_| anchor);
3088 // (
3089 // (start..end, new_text),
3090 // (insert_extra_newline, new_selection),
3091 // )
3092 // })
3093 // .unzip()
3094 // };
3095
3096 // this.edit_with_autoindent(edits, cx);
3097 // let buffer = this.buffer.read(cx).snapshot(cx);
3098 // let new_selections = selection_fixup_info
3099 // .into_iter()
3100 // .map(|(extra_newline_inserted, new_selection)| {
3101 // let mut cursor = new_selection.end.to_point(&buffer);
3102 // if extra_newline_inserted {
3103 // cursor.row -= 1;
3104 // cursor.column = buffer.line_len(cursor.row);
3105 // }
3106 // new_selection.map(|_| cursor)
3107 // })
3108 // .collect();
3109
3110 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3111 // this.refresh_copilot_suggestions(true, cx);
3112 // });
3113 // }
3114
3115 // pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3116 // let buffer = self.buffer.read(cx);
3117 // let snapshot = buffer.snapshot(cx);
3118
3119 // let mut edits = Vec::new();
3120 // let mut rows = Vec::new();
3121 // let mut rows_inserted = 0;
3122
3123 // for selection in self.selections.all_adjusted(cx) {
3124 // let cursor = selection.head();
3125 // let row = cursor.row;
3126
3127 // let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3128
3129 // let newline = "\n".to_string();
3130 // edits.push((start_of_line..start_of_line, newline));
3131
3132 // rows.push(row + rows_inserted);
3133 // rows_inserted += 1;
3134 // }
3135
3136 // self.transact(cx, |editor, cx| {
3137 // editor.edit(edits, cx);
3138
3139 // editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3140 // let mut index = 0;
3141 // s.move_cursors_with(|map, _, _| {
3142 // let row = rows[index];
3143 // index += 1;
3144
3145 // let point = Point::new(row, 0);
3146 // let boundary = map.next_line_boundary(point).1;
3147 // let clipped = map.clip_point(boundary, Bias::Left);
3148
3149 // (clipped, SelectionGoal::None)
3150 // });
3151 // });
3152
3153 // let mut indent_edits = Vec::new();
3154 // let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3155 // for row in rows {
3156 // let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3157 // for (row, indent) in indents {
3158 // if indent.len == 0 {
3159 // continue;
3160 // }
3161
3162 // let text = match indent.kind {
3163 // IndentKind::Space => " ".repeat(indent.len as usize),
3164 // IndentKind::Tab => "\t".repeat(indent.len as usize),
3165 // };
3166 // let point = Point::new(row, 0);
3167 // indent_edits.push((point..point, text));
3168 // }
3169 // }
3170 // editor.edit(indent_edits, cx);
3171 // });
3172 // }
3173
3174 // pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3175 // let buffer = self.buffer.read(cx);
3176 // let snapshot = buffer.snapshot(cx);
3177
3178 // let mut edits = Vec::new();
3179 // let mut rows = Vec::new();
3180 // let mut rows_inserted = 0;
3181
3182 // for selection in self.selections.all_adjusted(cx) {
3183 // let cursor = selection.head();
3184 // let row = cursor.row;
3185
3186 // let point = Point::new(row + 1, 0);
3187 // let start_of_line = snapshot.clip_point(point, Bias::Left);
3188
3189 // let newline = "\n".to_string();
3190 // edits.push((start_of_line..start_of_line, newline));
3191
3192 // rows_inserted += 1;
3193 // rows.push(row + rows_inserted);
3194 // }
3195
3196 // self.transact(cx, |editor, cx| {
3197 // editor.edit(edits, cx);
3198
3199 // editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3200 // let mut index = 0;
3201 // s.move_cursors_with(|map, _, _| {
3202 // let row = rows[index];
3203 // index += 1;
3204
3205 // let point = Point::new(row, 0);
3206 // let boundary = map.next_line_boundary(point).1;
3207 // let clipped = map.clip_point(boundary, Bias::Left);
3208
3209 // (clipped, SelectionGoal::None)
3210 // });
3211 // });
3212
3213 // let mut indent_edits = Vec::new();
3214 // let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3215 // for row in rows {
3216 // let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3217 // for (row, indent) in indents {
3218 // if indent.len == 0 {
3219 // continue;
3220 // }
3221
3222 // let text = match indent.kind {
3223 // IndentKind::Space => " ".repeat(indent.len as usize),
3224 // IndentKind::Tab => "\t".repeat(indent.len as usize),
3225 // };
3226 // let point = Point::new(row, 0);
3227 // indent_edits.push((point..point, text));
3228 // }
3229 // }
3230 // editor.edit(indent_edits, cx);
3231 // });
3232 // }
3233
3234 // pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3235 // self.insert_with_autoindent_mode(
3236 // text,
3237 // Some(AutoindentMode::Block {
3238 // original_indent_columns: Vec::new(),
3239 // }),
3240 // cx,
3241 // );
3242 // }
3243
3244 fn insert_with_autoindent_mode(
3245 &mut self,
3246 text: &str,
3247 autoindent_mode: Option<AutoindentMode>,
3248 cx: &mut ViewContext<Self>,
3249 ) {
3250 if self.read_only {
3251 return;
3252 }
3253
3254 let text: Arc<str> = text.into();
3255 self.transact(cx, |this, cx| {
3256 let old_selections = this.selections.all_adjusted(cx);
3257 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3258 let anchors = {
3259 let snapshot = buffer.read(cx);
3260 old_selections
3261 .iter()
3262 .map(|s| {
3263 let anchor = snapshot.anchor_after(s.head());
3264 s.map(|_| anchor)
3265 })
3266 .collect::<Vec<_>>()
3267 };
3268 buffer.edit(
3269 old_selections
3270 .iter()
3271 .map(|s| (s.start..s.end, text.clone())),
3272 autoindent_mode,
3273 cx,
3274 );
3275 anchors
3276 });
3277
3278 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3279 s.select_anchors(selection_anchors);
3280 })
3281 });
3282 }
3283
3284 // fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3285 // if !EditorSettings>(cx).show_completions_on_input {
3286 // return;
3287 // }
3288
3289 // let selection = self.selections.newest_anchor();
3290 // if self
3291 // .buffer
3292 // .read(cx)
3293 // .is_completion_trigger(selection.head(), text, cx)
3294 // {
3295 // self.show_completions(&ShowCompletions, cx);
3296 // } else {
3297 // self.hide_context_menu(cx);
3298 // }
3299 // }
3300
3301 // /// If any empty selections is touching the start of its innermost containing autoclose
3302 // /// region, expand it to select the brackets.
3303 // fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3304 // let selections = self.selections.all::<usize>(cx);
3305 // let buffer = self.buffer.read(cx).read(cx);
3306 // let mut new_selections = Vec::new();
3307 // for (mut selection, region) in self.selections_with_autoclose_regions(selections, &buffer) {
3308 // if let (Some(region), true) = (region, selection.is_empty()) {
3309 // let mut range = region.range.to_offset(&buffer);
3310 // if selection.start == range.start {
3311 // if range.start >= region.pair.start.len() {
3312 // range.start -= region.pair.start.len();
3313 // if buffer.contains_str_at(range.start, ®ion.pair.start) {
3314 // if buffer.contains_str_at(range.end, ®ion.pair.end) {
3315 // range.end += region.pair.end.len();
3316 // selection.start = range.start;
3317 // selection.end = range.end;
3318 // }
3319 // }
3320 // }
3321 // }
3322 // }
3323 // new_selections.push(selection);
3324 // }
3325
3326 // drop(buffer);
3327 // self.change_selections(None, cx, |selections| selections.select(new_selections));
3328 // }
3329
3330 // /// Iterate the given selections, and for each one, find the smallest surrounding
3331 // /// autoclose region. This uses the ordering of the selections and the autoclose
3332 // /// regions to avoid repeated comparisons.
3333 // fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3334 // &'a self,
3335 // selections: impl IntoIterator<Item = Selection<D>>,
3336 // buffer: &'a MultiBufferSnapshot,
3337 // ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3338 // let mut i = 0;
3339 // let mut regions = self.autoclose_regions.as_slice();
3340 // selections.into_iter().map(move |selection| {
3341 // let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3342
3343 // let mut enclosing = None;
3344 // while let Some(pair_state) = regions.get(i) {
3345 // if pair_state.range.end.to_offset(buffer) < range.start {
3346 // regions = ®ions[i + 1..];
3347 // i = 0;
3348 // } else if pair_state.range.start.to_offset(buffer) > range.end {
3349 // break;
3350 // } else {
3351 // if pair_state.selection_id == selection.id {
3352 // enclosing = Some(pair_state);
3353 // }
3354 // i += 1;
3355 // }
3356 // }
3357
3358 // (selection.clone(), enclosing)
3359 // })
3360 // }
3361
3362 /// Remove any autoclose regions that no longer contain their selection.
3363 fn invalidate_autoclose_regions(
3364 &mut self,
3365 mut selections: &[Selection<Anchor>],
3366 buffer: &MultiBufferSnapshot,
3367 ) {
3368 self.autoclose_regions.retain(|state| {
3369 let mut i = 0;
3370 while let Some(selection) = selections.get(i) {
3371 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3372 selections = &selections[1..];
3373 continue;
3374 }
3375 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3376 break;
3377 }
3378 if selection.id == state.selection_id {
3379 return true;
3380 } else {
3381 i += 1;
3382 }
3383 }
3384 false
3385 });
3386 }
3387
3388 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3389 let offset = position.to_offset(buffer);
3390 let (word_range, kind) = buffer.surrounding_word(offset);
3391 if offset > word_range.start && kind == Some(CharKind::Word) {
3392 Some(
3393 buffer
3394 .text_for_range(word_range.start..offset)
3395 .collect::<String>(),
3396 )
3397 } else {
3398 None
3399 }
3400 }
3401
3402 // pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3403 // todo!();
3404 // // self.refresh_inlay_hints(
3405 // // InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3406 // // cx,
3407 // // );
3408 // }
3409
3410 // pub fn inlay_hints_enabled(&self) -> bool {
3411 // todo!();
3412 // self.inlay_hint_cache.enabled
3413 // }
3414
3415 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3416 if self.project.is_none() || self.mode != EditorMode::Full {
3417 return;
3418 }
3419
3420 let reason_description = reason.description();
3421 let (invalidate_cache, required_languages) = match reason {
3422 InlayHintRefreshReason::Toggle(enabled) => {
3423 self.inlay_hint_cache.enabled = enabled;
3424 if enabled {
3425 (InvalidationStrategy::RefreshRequested, None)
3426 } else {
3427 self.inlay_hint_cache.clear();
3428 self.splice_inlay_hints(
3429 self.visible_inlay_hints(cx)
3430 .iter()
3431 .map(|inlay| inlay.id)
3432 .collect(),
3433 Vec::new(),
3434 cx,
3435 );
3436 return;
3437 }
3438 }
3439 InlayHintRefreshReason::SettingsChange(new_settings) => {
3440 match self.inlay_hint_cache.update_settings(
3441 &self.buffer,
3442 new_settings,
3443 self.visible_inlay_hints(cx),
3444 cx,
3445 ) {
3446 ControlFlow::Break(Some(InlaySplice {
3447 to_remove,
3448 to_insert,
3449 })) => {
3450 self.splice_inlay_hints(to_remove, to_insert, cx);
3451 return;
3452 }
3453 ControlFlow::Break(None) => return,
3454 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3455 }
3456 }
3457 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3458 if let Some(InlaySplice {
3459 to_remove,
3460 to_insert,
3461 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3462 {
3463 self.splice_inlay_hints(to_remove, to_insert, cx);
3464 }
3465 return;
3466 }
3467 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3468 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3469 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3470 }
3471 InlayHintRefreshReason::RefreshRequested => {
3472 (InvalidationStrategy::RefreshRequested, None)
3473 }
3474 };
3475
3476 if let Some(InlaySplice {
3477 to_remove,
3478 to_insert,
3479 }) = self.inlay_hint_cache.spawn_hint_refresh(
3480 reason_description,
3481 self.excerpt_visible_offsets(required_languages.as_ref(), cx),
3482 invalidate_cache,
3483 cx,
3484 ) {
3485 self.splice_inlay_hints(to_remove, to_insert, cx);
3486 }
3487 }
3488
3489 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3490 self.display_map
3491 .read(cx)
3492 .current_inlays()
3493 .filter(move |inlay| {
3494 Some(inlay.id) != self.copilot_state.suggestion.as_ref().map(|h| h.id)
3495 })
3496 .cloned()
3497 .collect()
3498 }
3499
3500 pub fn excerpt_visible_offsets(
3501 &self,
3502 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3503 cx: &mut ViewContext<Editor>,
3504 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3505 let multi_buffer = self.buffer().read(cx);
3506 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3507 let multi_buffer_visible_start = self
3508 .scroll_manager
3509 .anchor()
3510 .anchor
3511 .to_point(&multi_buffer_snapshot);
3512 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3513 multi_buffer_visible_start
3514 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3515 Bias::Left,
3516 );
3517 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3518 multi_buffer
3519 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3520 .into_iter()
3521 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3522 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3523 let buffer = buffer_handle.read(cx);
3524 let language = buffer.language()?;
3525 if let Some(restrict_to_languages) = restrict_to_languages {
3526 if !restrict_to_languages.contains(language) {
3527 return None;
3528 }
3529 }
3530 Some((
3531 excerpt_id,
3532 (
3533 buffer_handle,
3534 buffer.version().clone(),
3535 excerpt_visible_range,
3536 ),
3537 ))
3538 })
3539 .collect()
3540 }
3541
3542 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3543 TextLayoutDetails {
3544 text_system: cx.text_system().clone(),
3545 editor_style: self.style.clone().unwrap(),
3546 }
3547 }
3548
3549 fn splice_inlay_hints(
3550 &self,
3551 to_remove: Vec<InlayId>,
3552 to_insert: Vec<Inlay>,
3553 cx: &mut ViewContext<Self>,
3554 ) {
3555 self.display_map.update(cx, |display_map, cx| {
3556 display_map.splice_inlays(to_remove, to_insert, cx);
3557 });
3558 cx.notify();
3559 }
3560
3561 // fn trigger_on_type_formatting(
3562 // &self,
3563 // input: String,
3564 // cx: &mut ViewContext<Self>,
3565 // ) -> Option<Task<Result<()>>> {
3566 // if input.len() != 1 {
3567 // return None;
3568 // }
3569
3570 // let project = self.project.as_ref()?;
3571 // let position = self.selections.newest_anchor().head();
3572 // let (buffer, buffer_position) = self
3573 // .buffer
3574 // .read(cx)
3575 // .text_anchor_for_position(position.clone(), cx)?;
3576
3577 // // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3578 // // hence we do LSP request & edit on host side only — add formats to host's history.
3579 // let push_to_lsp_host_history = true;
3580 // // If this is not the host, append its history with new edits.
3581 // let push_to_client_history = project.read(cx).is_remote();
3582
3583 // let on_type_formatting = project.update(cx, |project, cx| {
3584 // project.on_type_format(
3585 // buffer.clone(),
3586 // buffer_position,
3587 // input,
3588 // push_to_lsp_host_history,
3589 // cx,
3590 // )
3591 // });
3592 // Some(cx.spawn(|editor, mut cx| async move {
3593 // if let Some(transaction) = on_type_formatting.await? {
3594 // if push_to_client_history {
3595 // buffer.update(&mut cx, |buffer, _| {
3596 // buffer.push_transaction(transaction, Instant::now());
3597 // });
3598 // }
3599 // editor.update(&mut cx, |editor, cx| {
3600 // editor.refresh_document_highlights(cx);
3601 // })?;
3602 // }
3603 // Ok(())
3604 // }))
3605 // }
3606
3607 fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3608 if self.pending_rename.is_some() {
3609 return;
3610 }
3611
3612 let project = if let Some(project) = self.project.clone() {
3613 project
3614 } else {
3615 return;
3616 };
3617
3618 let position = self.selections.newest_anchor().head();
3619 let (buffer, buffer_position) = if let Some(output) = self
3620 .buffer
3621 .read(cx)
3622 .text_anchor_for_position(position.clone(), cx)
3623 {
3624 output
3625 } else {
3626 return;
3627 };
3628
3629 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
3630 let completions = project.update(cx, |project, cx| {
3631 project.completions(&buffer, buffer_position, cx)
3632 });
3633
3634 let id = post_inc(&mut self.next_completion_id);
3635 let task = cx.spawn(|this, mut cx| {
3636 async move {
3637 let menu = if let Some(completions) = completions.await.log_err() {
3638 let mut menu = CompletionsMenu {
3639 id,
3640 initial_position: position,
3641 match_candidates: completions
3642 .iter()
3643 .enumerate()
3644 .map(|(id, completion)| {
3645 StringMatchCandidate::new(
3646 id,
3647 completion.label.text[completion.label.filter_range.clone()]
3648 .into(),
3649 )
3650 })
3651 .collect(),
3652 buffer,
3653 completions: Arc::new(RwLock::new(completions.into())),
3654 matches: Vec::new().into(),
3655 selected_item: 0,
3656 list: Default::default(),
3657 };
3658 menu.filter(query.as_deref(), cx.background_executor().clone())
3659 .await;
3660 if menu.matches.is_empty() {
3661 None
3662 } else {
3663 _ = this.update(&mut cx, |editor, cx| {
3664 menu.pre_resolve_completion_documentation(editor.project.clone(), cx);
3665 });
3666 Some(menu)
3667 }
3668 } else {
3669 None
3670 };
3671
3672 this.update(&mut cx, |this, cx| {
3673 this.completion_tasks.retain(|(task_id, _)| *task_id > id);
3674
3675 let mut context_menu = this.context_menu.write();
3676 match context_menu.as_ref() {
3677 None => {}
3678
3679 Some(ContextMenu::Completions(prev_menu)) => {
3680 if prev_menu.id > id {
3681 return;
3682 }
3683 }
3684
3685 _ => return,
3686 }
3687
3688 if this.focus_handle.is_focused(cx) && menu.is_some() {
3689 let menu = menu.unwrap();
3690 *context_menu = Some(ContextMenu::Completions(menu));
3691 drop(context_menu);
3692 this.discard_copilot_suggestion(cx);
3693 cx.notify();
3694 } else if this.completion_tasks.is_empty() {
3695 // If there are no more completion tasks and the last menu was
3696 // empty, we should hide it. If it was already hidden, we should
3697 // also show the copilot suggestion when available.
3698 drop(context_menu);
3699 if this.hide_context_menu(cx).is_none() {
3700 this.update_visible_copilot_suggestion(cx);
3701 }
3702 }
3703 })?;
3704
3705 Ok::<_, anyhow::Error>(())
3706 }
3707 .log_err()
3708 });
3709 self.completion_tasks.push((id, task));
3710 }
3711
3712 // pub fn confirm_completion(
3713 // &mut self,
3714 // action: &ConfirmCompletion,
3715 // cx: &mut ViewContext<Self>,
3716 // ) -> Option<Task<Result<()>>> {
3717 // use language::ToOffset as _;
3718
3719 // let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3720 // menu
3721 // } else {
3722 // return None;
3723 // };
3724
3725 // let mat = completions_menu
3726 // .matches
3727 // .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3728 // let buffer_handle = completions_menu.buffer;
3729 // let completions = completions_menu.completions.read();
3730 // let completion = completions.get(mat.candidate_id)?;
3731
3732 // let snippet;
3733 // let text;
3734 // if completion.is_snippet() {
3735 // snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3736 // text = snippet.as_ref().unwrap().text.clone();
3737 // } else {
3738 // snippet = None;
3739 // text = completion.new_text.clone();
3740 // };
3741 // let selections = self.selections.all::<usize>(cx);
3742 // let buffer = buffer_handle.read(cx);
3743 // let old_range = completion.old_range.to_offset(buffer);
3744 // let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3745
3746 // let newest_selection = self.selections.newest_anchor();
3747 // if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3748 // return None;
3749 // }
3750
3751 // let lookbehind = newest_selection
3752 // .start
3753 // .text_anchor
3754 // .to_offset(buffer)
3755 // .saturating_sub(old_range.start);
3756 // let lookahead = old_range
3757 // .end
3758 // .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3759 // let mut common_prefix_len = old_text
3760 // .bytes()
3761 // .zip(text.bytes())
3762 // .take_while(|(a, b)| a == b)
3763 // .count();
3764
3765 // let snapshot = self.buffer.read(cx).snapshot(cx);
3766 // let mut range_to_replace: Option<Range<isize>> = None;
3767 // let mut ranges = Vec::new();
3768 // for selection in &selections {
3769 // if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3770 // let start = selection.start.saturating_sub(lookbehind);
3771 // let end = selection.end + lookahead;
3772 // if selection.id == newest_selection.id {
3773 // range_to_replace = Some(
3774 // ((start + common_prefix_len) as isize - selection.start as isize)
3775 // ..(end as isize - selection.start as isize),
3776 // );
3777 // }
3778 // ranges.push(start + common_prefix_len..end);
3779 // } else {
3780 // common_prefix_len = 0;
3781 // ranges.clear();
3782 // ranges.extend(selections.iter().map(|s| {
3783 // if s.id == newest_selection.id {
3784 // range_to_replace = Some(
3785 // old_range.start.to_offset_utf16(&snapshot).0 as isize
3786 // - selection.start as isize
3787 // ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3788 // - selection.start as isize,
3789 // );
3790 // old_range.clone()
3791 // } else {
3792 // s.start..s.end
3793 // }
3794 // }));
3795 // break;
3796 // }
3797 // }
3798 // let text = &text[common_prefix_len..];
3799
3800 // cx.emit(Event::InputHandled {
3801 // utf16_range_to_replace: range_to_replace,
3802 // text: text.into(),
3803 // });
3804
3805 // self.transact(cx, |this, cx| {
3806 // if let Some(mut snippet) = snippet {
3807 // snippet.text = text.to_string();
3808 // for tabstop in snippet.tabstops.iter_mut().flatten() {
3809 // tabstop.start -= common_prefix_len as isize;
3810 // tabstop.end -= common_prefix_len as isize;
3811 // }
3812
3813 // this.insert_snippet(&ranges, snippet, cx).log_err();
3814 // } else {
3815 // this.buffer.update(cx, |buffer, cx| {
3816 // buffer.edit(
3817 // ranges.iter().map(|range| (range.clone(), text)),
3818 // this.autoindent_mode.clone(),
3819 // cx,
3820 // );
3821 // });
3822 // }
3823
3824 // this.refresh_copilot_suggestions(true, cx);
3825 // });
3826
3827 // let project = self.project.clone()?;
3828 // let apply_edits = project.update(cx, |project, cx| {
3829 // project.apply_additional_edits_for_completion(
3830 // buffer_handle,
3831 // completion.clone(),
3832 // true,
3833 // cx,
3834 // )
3835 // });
3836 // Some(cx.foreground().spawn(async move {
3837 // apply_edits.await?;
3838 // Ok(())
3839 // }))
3840 // }
3841
3842 // pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3843 // let mut context_menu = self.context_menu.write();
3844 // if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
3845 // *context_menu = None;
3846 // cx.notify();
3847 // return;
3848 // }
3849 // drop(context_menu);
3850
3851 // let deployed_from_indicator = action.deployed_from_indicator;
3852 // let mut task = self.code_actions_task.take();
3853 // cx.spawn(|this, mut cx| async move {
3854 // while let Some(prev_task) = task {
3855 // prev_task.await;
3856 // task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
3857 // }
3858
3859 // this.update(&mut cx, |this, cx| {
3860 // if this.focused {
3861 // if let Some((buffer, actions)) = this.available_code_actions.clone() {
3862 // this.completion_tasks.clear();
3863 // this.discard_copilot_suggestion(cx);
3864 // *this.context_menu.write() =
3865 // Some(ContextMenu::CodeActions(CodeActionsMenu {
3866 // buffer,
3867 // actions,
3868 // selected_item: Default::default(),
3869 // list: Default::default(),
3870 // deployed_from_indicator,
3871 // }));
3872 // }
3873 // }
3874 // })?;
3875
3876 // Ok::<_, anyhow::Error>(())
3877 // })
3878 // .detach_and_log_err(cx);
3879 // }
3880
3881 // pub fn confirm_code_action(
3882 // workspace: &mut Workspace,
3883 // action: &ConfirmCodeAction,
3884 // cx: &mut ViewContext<Workspace>,
3885 // ) -> Option<Task<Result<()>>> {
3886 // let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
3887 // let actions_menu = if let ContextMenu::CodeActions(menu) =
3888 // editor.update(cx, |editor, cx| editor.hide_context_menu(cx))?
3889 // {
3890 // menu
3891 // } else {
3892 // return None;
3893 // };
3894 // let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
3895 // let action = actions_menu.actions.get(action_ix)?.clone();
3896 // let title = action.lsp_action.title.clone();
3897 // let buffer = actions_menu.buffer;
3898
3899 // let apply_code_actions = workspace.project().clone().update(cx, |project, cx| {
3900 // project.apply_code_action(buffer, action, true, cx)
3901 // });
3902 // let editor = editor.downgrade();
3903 // Some(cx.spawn(|workspace, cx| async move {
3904 // let project_transaction = apply_code_actions.await?;
3905 // Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
3906 // }))
3907 // }
3908
3909 // async fn open_project_transaction(
3910 // this: &WeakViewHandle<Editor
3911 // workspace: WeakViewHandle<Workspace
3912 // transaction: ProjectTransaction,
3913 // title: String,
3914 // mut cx: AsyncAppContext,
3915 // ) -> Result<()> {
3916 // let replica_id = this.read_with(&cx, |this, cx| this.replica_id(cx))?;
3917
3918 // let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
3919 // entries.sort_unstable_by_key(|(buffer, _)| {
3920 // buffer.read_with(&cx, |buffer, _| buffer.file().map(|f| f.path().clone()))
3921 // });
3922
3923 // // If the project transaction's edits are all contained within this editor, then
3924 // // avoid opening a new editor to display them.
3925
3926 // if let Some((buffer, transaction)) = entries.first() {
3927 // if entries.len() == 1 {
3928 // let excerpt = this.read_with(&cx, |editor, cx| {
3929 // editor
3930 // .buffer()
3931 // .read(cx)
3932 // .excerpt_containing(editor.selections.newest_anchor().head(), cx)
3933 // })?;
3934 // if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
3935 // if excerpted_buffer == *buffer {
3936 // let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
3937 // let excerpt_range = excerpt_range.to_offset(buffer);
3938 // buffer
3939 // .edited_ranges_for_transaction::<usize>(transaction)
3940 // .all(|range| {
3941 // excerpt_range.start <= range.start
3942 // && excerpt_range.end >= range.end
3943 // })
3944 // });
3945
3946 // if all_edits_within_excerpt {
3947 // return Ok(());
3948 // }
3949 // }
3950 // }
3951 // }
3952 // } else {
3953 // return Ok(());
3954 // }
3955
3956 // let mut ranges_to_highlight = Vec::new();
3957 // let excerpt_buffer = cx.build_model(|cx| {
3958 // let mut multibuffer = MultiBuffer::new(replica_id).with_title(title);
3959 // for (buffer_handle, transaction) in &entries {
3960 // let buffer = buffer_handle.read(cx);
3961 // ranges_to_highlight.extend(
3962 // multibuffer.push_excerpts_with_context_lines(
3963 // buffer_handle.clone(),
3964 // buffer
3965 // .edited_ranges_for_transaction::<usize>(transaction)
3966 // .collect(),
3967 // 1,
3968 // cx,
3969 // ),
3970 // );
3971 // }
3972 // multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
3973 // multibuffer
3974 // });
3975
3976 // workspace.update(&mut cx, |workspace, cx| {
3977 // let project = workspace.project().clone();
3978 // let editor =
3979 // cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
3980 // workspace.add_item(Box::new(editor.clone()), cx);
3981 // editor.update(cx, |editor, cx| {
3982 // editor.highlight_background::<Self>(
3983 // ranges_to_highlight,
3984 // |theme| theme.editor.highlighted_line_background,
3985 // cx,
3986 // );
3987 // });
3988 // })?;
3989
3990 // Ok(())
3991 // }
3992
3993 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3994 let project = self.project.clone()?;
3995 let buffer = self.buffer.read(cx);
3996 let newest_selection = self.selections.newest_anchor().clone();
3997 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
3998 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
3999 if start_buffer != end_buffer {
4000 return None;
4001 }
4002
4003 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4004 cx.background_executor()
4005 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4006 .await;
4007
4008 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4009 project.code_actions(&start_buffer, start..end, cx)
4010 }) {
4011 code_actions.await.log_err()
4012 } else {
4013 None
4014 };
4015
4016 this.update(&mut cx, |this, cx| {
4017 this.available_code_actions = actions.and_then(|actions| {
4018 if actions.is_empty() {
4019 None
4020 } else {
4021 Some((start_buffer, actions.into()))
4022 }
4023 });
4024 cx.notify();
4025 })
4026 .log_err();
4027 }));
4028 None
4029 }
4030
4031 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4032 if self.pending_rename.is_some() {
4033 return None;
4034 }
4035
4036 let project = self.project.clone()?;
4037 let buffer = self.buffer.read(cx);
4038 let newest_selection = self.selections.newest_anchor().clone();
4039 let cursor_position = newest_selection.head();
4040 let (cursor_buffer, cursor_buffer_position) =
4041 buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
4042 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4043 if cursor_buffer != tail_buffer {
4044 return None;
4045 }
4046
4047 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4048 cx.background_executor()
4049 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4050 .await;
4051
4052 let highlights = if let Some(highlights) = project
4053 .update(&mut cx, |project, cx| {
4054 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4055 })
4056 .log_err()
4057 {
4058 highlights.await.log_err()
4059 } else {
4060 None
4061 };
4062
4063 if let Some(highlights) = highlights {
4064 this.update(&mut cx, |this, cx| {
4065 if this.pending_rename.is_some() {
4066 return;
4067 }
4068
4069 let buffer_id = cursor_position.buffer_id;
4070 let buffer = this.buffer.read(cx);
4071 if !buffer
4072 .text_anchor_for_position(cursor_position, cx)
4073 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4074 {
4075 return;
4076 }
4077
4078 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4079 let mut write_ranges = Vec::new();
4080 let mut read_ranges = Vec::new();
4081 for highlight in highlights {
4082 for (excerpt_id, excerpt_range) in
4083 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4084 {
4085 let start = highlight
4086 .range
4087 .start
4088 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4089 let end = highlight
4090 .range
4091 .end
4092 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4093 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4094 continue;
4095 }
4096
4097 let range = Anchor {
4098 buffer_id,
4099 excerpt_id: excerpt_id.clone(),
4100 text_anchor: start,
4101 }..Anchor {
4102 buffer_id,
4103 excerpt_id,
4104 text_anchor: end,
4105 };
4106 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4107 write_ranges.push(range);
4108 } else {
4109 read_ranges.push(range);
4110 }
4111 }
4112 }
4113
4114 this.highlight_background::<DocumentHighlightRead>(
4115 read_ranges,
4116 |theme| theme.editor_document_highlight_read_background,
4117 cx,
4118 );
4119 this.highlight_background::<DocumentHighlightWrite>(
4120 write_ranges,
4121 |theme| theme.editor_document_highlight_write_background,
4122 cx,
4123 );
4124 cx.notify();
4125 })
4126 .log_err();
4127 }
4128 }));
4129 None
4130 }
4131
4132 fn refresh_copilot_suggestions(
4133 &mut self,
4134 debounce: bool,
4135 cx: &mut ViewContext<Self>,
4136 ) -> Option<()> {
4137 let copilot = Copilot::global(cx)?;
4138 if self.mode != EditorMode::Full || !copilot.read(cx).status().is_authorized() {
4139 self.clear_copilot_suggestions(cx);
4140 return None;
4141 }
4142 self.update_visible_copilot_suggestion(cx);
4143
4144 let snapshot = self.buffer.read(cx).snapshot(cx);
4145 let cursor = self.selections.newest_anchor().head();
4146 if !self.is_copilot_enabled_at(cursor, &snapshot, cx) {
4147 self.clear_copilot_suggestions(cx);
4148 return None;
4149 }
4150
4151 let (buffer, buffer_position) =
4152 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4153 self.copilot_state.pending_refresh = cx.spawn(|this, mut cx| async move {
4154 if debounce {
4155 cx.background_executor()
4156 .timer(COPILOT_DEBOUNCE_TIMEOUT)
4157 .await;
4158 }
4159
4160 let completions = copilot
4161 .update(&mut cx, |copilot, cx| {
4162 copilot.completions(&buffer, buffer_position, cx)
4163 })
4164 .log_err()
4165 .unwrap_or(Task::ready(Ok(Vec::new())))
4166 .await
4167 .log_err()
4168 .into_iter()
4169 .flatten()
4170 .collect_vec();
4171
4172 this.update(&mut cx, |this, cx| {
4173 if !completions.is_empty() {
4174 this.copilot_state.cycled = false;
4175 this.copilot_state.pending_cycling_refresh = Task::ready(None);
4176 this.copilot_state.completions.clear();
4177 this.copilot_state.active_completion_index = 0;
4178 this.copilot_state.excerpt_id = Some(cursor.excerpt_id);
4179 for completion in completions {
4180 this.copilot_state.push_completion(completion);
4181 }
4182 this.update_visible_copilot_suggestion(cx);
4183 }
4184 })
4185 .log_err()?;
4186 Some(())
4187 });
4188
4189 Some(())
4190 }
4191
4192 fn cycle_copilot_suggestions(
4193 &mut self,
4194 direction: Direction,
4195 cx: &mut ViewContext<Self>,
4196 ) -> Option<()> {
4197 let copilot = Copilot::global(cx)?;
4198 if self.mode != EditorMode::Full || !copilot.read(cx).status().is_authorized() {
4199 return None;
4200 }
4201
4202 if self.copilot_state.cycled {
4203 self.copilot_state.cycle_completions(direction);
4204 self.update_visible_copilot_suggestion(cx);
4205 } else {
4206 let cursor = self.selections.newest_anchor().head();
4207 let (buffer, buffer_position) =
4208 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4209 self.copilot_state.pending_cycling_refresh = cx.spawn(|this, mut cx| async move {
4210 let completions = copilot
4211 .update(&mut cx, |copilot, cx| {
4212 copilot.completions_cycling(&buffer, buffer_position, cx)
4213 })
4214 .log_err()?
4215 .await;
4216
4217 this.update(&mut cx, |this, cx| {
4218 this.copilot_state.cycled = true;
4219 for completion in completions.log_err().into_iter().flatten() {
4220 this.copilot_state.push_completion(completion);
4221 }
4222 this.copilot_state.cycle_completions(direction);
4223 this.update_visible_copilot_suggestion(cx);
4224 })
4225 .log_err()?;
4226
4227 Some(())
4228 });
4229 }
4230
4231 Some(())
4232 }
4233
4234 fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {
4235 if !self.has_active_copilot_suggestion(cx) {
4236 self.refresh_copilot_suggestions(false, cx);
4237 return;
4238 }
4239
4240 self.update_visible_copilot_suggestion(cx);
4241 }
4242
4243 fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {
4244 if self.has_active_copilot_suggestion(cx) {
4245 self.cycle_copilot_suggestions(Direction::Next, cx);
4246 } else {
4247 let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
4248 if is_copilot_disabled {
4249 todo!();
4250 // cx.propagate();
4251 }
4252 }
4253 }
4254
4255 fn previous_copilot_suggestion(
4256 &mut self,
4257 _: &copilot::PreviousSuggestion,
4258 cx: &mut ViewContext<Self>,
4259 ) {
4260 if self.has_active_copilot_suggestion(cx) {
4261 self.cycle_copilot_suggestions(Direction::Prev, cx);
4262 } else {
4263 let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
4264 if is_copilot_disabled {
4265 todo!();
4266 // cx.propagate();
4267 }
4268 }
4269 }
4270
4271 fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
4272 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
4273 if let Some((copilot, completion)) =
4274 Copilot::global(cx).zip(self.copilot_state.active_completion())
4275 {
4276 copilot
4277 .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
4278 .detach_and_log_err(cx);
4279
4280 self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
4281 }
4282 cx.emit(Event::InputHandled {
4283 utf16_range_to_replace: None,
4284 text: suggestion.text.to_string().into(),
4285 });
4286 self.insert_with_autoindent_mode(&suggestion.text.to_string(), None, cx);
4287 cx.notify();
4288 true
4289 } else {
4290 false
4291 }
4292 }
4293
4294 fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
4295 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
4296 if let Some(copilot) = Copilot::global(cx) {
4297 copilot
4298 .update(cx, |copilot, cx| {
4299 copilot.discard_completions(&self.copilot_state.completions, cx)
4300 })
4301 .detach_and_log_err(cx);
4302
4303 self.report_copilot_event(None, false, cx)
4304 }
4305
4306 self.display_map.update(cx, |map, cx| {
4307 map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
4308 });
4309 cx.notify();
4310 true
4311 } else {
4312 false
4313 }
4314 }
4315
4316 fn is_copilot_enabled_at(
4317 &self,
4318 location: Anchor,
4319 snapshot: &MultiBufferSnapshot,
4320 cx: &mut ViewContext<Self>,
4321 ) -> bool {
4322 let file = snapshot.file_at(location);
4323 let language = snapshot.language_at(location);
4324 let settings = all_language_settings(file, cx);
4325 settings.copilot_enabled(language, file.map(|f| f.path().as_ref()))
4326 }
4327
4328 fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
4329 if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
4330 let buffer = self.buffer.read(cx).read(cx);
4331 suggestion.position.is_valid(&buffer)
4332 } else {
4333 false
4334 }
4335 }
4336
4337 fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4338 let suggestion = self.copilot_state.suggestion.take()?;
4339 self.display_map.update(cx, |map, cx| {
4340 map.splice_inlays(vec![suggestion.id], Default::default(), cx);
4341 });
4342 let buffer = self.buffer.read(cx).read(cx);
4343
4344 if suggestion.position.is_valid(&buffer) {
4345 Some(suggestion)
4346 } else {
4347 None
4348 }
4349 }
4350
4351 fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
4352 let snapshot = self.buffer.read(cx).snapshot(cx);
4353 let selection = self.selections.newest_anchor();
4354 let cursor = selection.head();
4355
4356 if self.context_menu.read().is_some()
4357 || !self.completion_tasks.is_empty()
4358 || selection.start != selection.end
4359 {
4360 self.discard_copilot_suggestion(cx);
4361 } else if let Some(text) = self
4362 .copilot_state
4363 .text_for_active_completion(cursor, &snapshot)
4364 {
4365 let text = Rope::from(text);
4366 let mut to_remove = Vec::new();
4367 if let Some(suggestion) = self.copilot_state.suggestion.take() {
4368 to_remove.push(suggestion.id);
4369 }
4370
4371 let suggestion_inlay =
4372 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4373 self.copilot_state.suggestion = Some(suggestion_inlay.clone());
4374 self.display_map.update(cx, move |map, cx| {
4375 map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
4376 });
4377 cx.notify();
4378 } else {
4379 self.discard_copilot_suggestion(cx);
4380 }
4381 }
4382
4383 fn clear_copilot_suggestions(&mut self, cx: &mut ViewContext<Self>) {
4384 self.copilot_state = Default::default();
4385 self.discard_copilot_suggestion(cx);
4386 }
4387
4388 // pub fn render_code_actions_indicator(
4389 // &self,
4390 // style: &EditorStyle,
4391 // is_active: bool,
4392 // cx: &mut ViewContext<Self>,
4393 // ) -> Option<AnyElement<Self>> {
4394 // if self.available_code_actions.is_some() {
4395 // enum CodeActions {}
4396 // Some(
4397 // MouseEventHandler::new::<CodeActions, _>(0, cx, |state, _| {
4398 // Svg::new("icons/bolt.svg").with_color(
4399 // style
4400 // .code_actions
4401 // .indicator
4402 // .in_state(is_active)
4403 // .style_for(state)
4404 // .color,
4405 // )
4406 // })
4407 // .with_cursor_style(CursorStyle::PointingHand)
4408 // .with_padding(Padding::uniform(3.))
4409 // .on_down(MouseButton::Left, |_, this, cx| {
4410 // this.toggle_code_actions(
4411 // &ToggleCodeActions {
4412 // deployed_from_indicator: true,
4413 // },
4414 // cx,
4415 // );
4416 // })
4417 // .into_any(),
4418 // )
4419 // } else {
4420 // None
4421 // }
4422 // }
4423
4424 // pub fn render_fold_indicators(
4425 // &self,
4426 // fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
4427 // style: &EditorStyle,
4428 // gutter_hovered: bool,
4429 // line_height: f32,
4430 // gutter_margin: f32,
4431 // cx: &mut ViewContext<Self>,
4432 // ) -> Vec<Option<AnyElement<Self>>> {
4433 // enum FoldIndicators {}
4434
4435 // let style = style.folds.clone();
4436
4437 // fold_data
4438 // .iter()
4439 // .enumerate()
4440 // .map(|(ix, fold_data)| {
4441 // fold_data
4442 // .map(|(fold_status, buffer_row, active)| {
4443 // (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
4444 // MouseEventHandler::new::<FoldIndicators, _>(
4445 // ix as usize,
4446 // cx,
4447 // |mouse_state, _| {
4448 // Svg::new(match fold_status {
4449 // FoldStatus::Folded => style.folded_icon.clone(),
4450 // FoldStatus::Foldable => style.foldable_icon.clone(),
4451 // })
4452 // .with_color(
4453 // style
4454 // .indicator
4455 // .in_state(fold_status == FoldStatus::Folded)
4456 // .style_for(mouse_state)
4457 // .color,
4458 // )
4459 // .constrained()
4460 // .with_width(gutter_margin * style.icon_margin_scale)
4461 // .aligned()
4462 // .constrained()
4463 // .with_height(line_height)
4464 // .with_width(gutter_margin)
4465 // .aligned()
4466 // },
4467 // )
4468 // .with_cursor_style(CursorStyle::PointingHand)
4469 // .with_padding(Padding::uniform(3.))
4470 // .on_click(MouseButton::Left, {
4471 // move |_, editor, cx| match fold_status {
4472 // FoldStatus::Folded => {
4473 // editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4474 // }
4475 // FoldStatus::Foldable => {
4476 // editor.fold_at(&FoldAt { buffer_row }, cx);
4477 // }
4478 // }
4479 // })
4480 // .into_any()
4481 // })
4482 // })
4483 // .flatten()
4484 // })
4485 // .collect()
4486 // }
4487
4488 pub fn context_menu_visible(&self) -> bool {
4489 false
4490 // todo!("context menu")
4491 // self.context_menu
4492 // .read()
4493 // .as_ref()
4494 // .map_or(false, |menu| menu.visible())
4495 }
4496
4497 // pub fn render_context_menu(
4498 // &self,
4499 // cursor_position: DisplayPoint,
4500 // style: EditorStyle,
4501 // cx: &mut ViewContext<Editor>,
4502 // ) -> Option<(DisplayPoint, AnyElement<Editor>)> {
4503 // self.context_menu.read().as_ref().map(|menu| {
4504 // menu.render(
4505 // cursor_position,
4506 // style,
4507 // self.workspace.as_ref().map(|(w, _)| w.clone()),
4508 // cx,
4509 // )
4510 // })
4511 // }
4512
4513 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4514 cx.notify();
4515 self.completion_tasks.clear();
4516 let context_menu = self.context_menu.write().take();
4517 if context_menu.is_some() {
4518 self.update_visible_copilot_suggestion(cx);
4519 }
4520 context_menu
4521 }
4522
4523 // pub fn insert_snippet(
4524 // &mut self,
4525 // insertion_ranges: &[Range<usize>],
4526 // snippet: Snippet,
4527 // cx: &mut ViewContext<Self>,
4528 // ) -> Result<()> {
4529 // let tabstops = self.buffer.update(cx, |buffer, cx| {
4530 // let snippet_text: Arc<str> = snippet.text.clone().into();
4531 // buffer.edit(
4532 // insertion_ranges
4533 // .iter()
4534 // .cloned()
4535 // .map(|range| (range, snippet_text.clone())),
4536 // Some(AutoindentMode::EachLine),
4537 // cx,
4538 // );
4539
4540 // let snapshot = &*buffer.read(cx);
4541 // let snippet = &snippet;
4542 // snippet
4543 // .tabstops
4544 // .iter()
4545 // .map(|tabstop| {
4546 // let mut tabstop_ranges = tabstop
4547 // .iter()
4548 // .flat_map(|tabstop_range| {
4549 // let mut delta = 0_isize;
4550 // insertion_ranges.iter().map(move |insertion_range| {
4551 // let insertion_start = insertion_range.start as isize + delta;
4552 // delta +=
4553 // snippet.text.len() as isize - insertion_range.len() as isize;
4554
4555 // let start = snapshot.anchor_before(
4556 // (insertion_start + tabstop_range.start) as usize,
4557 // );
4558 // let end = snapshot
4559 // .anchor_after((insertion_start + tabstop_range.end) as usize);
4560 // start..end
4561 // })
4562 // })
4563 // .collect::<Vec<_>>();
4564 // tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4565 // tabstop_ranges
4566 // })
4567 // .collect::<Vec<_>>()
4568 // });
4569
4570 // if let Some(tabstop) = tabstops.first() {
4571 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4572 // s.select_ranges(tabstop.iter().cloned());
4573 // });
4574 // self.snippet_stack.push(SnippetState {
4575 // active_index: 0,
4576 // ranges: tabstops,
4577 // });
4578 // }
4579
4580 // Ok(())
4581 // }
4582
4583 // pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4584 // self.move_to_snippet_tabstop(Bias::Right, cx)
4585 // }
4586
4587 // pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4588 // self.move_to_snippet_tabstop(Bias::Left, cx)
4589 // }
4590
4591 // pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4592 // if let Some(mut snippet) = self.snippet_stack.pop() {
4593 // match bias {
4594 // Bias::Left => {
4595 // if snippet.active_index > 0 {
4596 // snippet.active_index -= 1;
4597 // } else {
4598 // self.snippet_stack.push(snippet);
4599 // return false;
4600 // }
4601 // }
4602 // Bias::Right => {
4603 // if snippet.active_index + 1 < snippet.ranges.len() {
4604 // snippet.active_index += 1;
4605 // } else {
4606 // self.snippet_stack.push(snippet);
4607 // return false;
4608 // }
4609 // }
4610 // }
4611 // if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4612 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4613 // s.select_anchor_ranges(current_ranges.iter().cloned())
4614 // });
4615 // // If snippet state is not at the last tabstop, push it back on the stack
4616 // if snippet.active_index + 1 < snippet.ranges.len() {
4617 // self.snippet_stack.push(snippet);
4618 // }
4619 // return true;
4620 // }
4621 // }
4622
4623 // false
4624 // }
4625
4626 // pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4627 // self.transact(cx, |this, cx| {
4628 // this.select_all(&SelectAll, cx);
4629 // this.insert("", cx);
4630 // });
4631 // }
4632
4633 // pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4634 // self.transact(cx, |this, cx| {
4635 // this.select_autoclose_pair(cx);
4636 // let mut selections = this.selections.all::<Point>(cx);
4637 // if !this.selections.line_mode {
4638 // let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4639 // for selection in &mut selections {
4640 // if selection.is_empty() {
4641 // let old_head = selection.head();
4642 // let mut new_head =
4643 // movement::left(&display_map, old_head.to_display_point(&display_map))
4644 // .to_point(&display_map);
4645 // if let Some((buffer, line_buffer_range)) = display_map
4646 // .buffer_snapshot
4647 // .buffer_line_for_row(old_head.row)
4648 // {
4649 // let indent_size =
4650 // buffer.indent_size_for_line(line_buffer_range.start.row);
4651 // let indent_len = match indent_size.kind {
4652 // IndentKind::Space => {
4653 // buffer.settings_at(line_buffer_range.start, cx).tab_size
4654 // }
4655 // IndentKind::Tab => NonZeroU32::new(1).unwrap(),
4656 // };
4657 // if old_head.column <= indent_size.len && old_head.column > 0 {
4658 // let indent_len = indent_len.get();
4659 // new_head = cmp::min(
4660 // new_head,
4661 // Point::new(
4662 // old_head.row,
4663 // ((old_head.column - 1) / indent_len) * indent_len,
4664 // ),
4665 // );
4666 // }
4667 // }
4668
4669 // selection.set_head(new_head, SelectionGoal::None);
4670 // }
4671 // }
4672 // }
4673
4674 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4675 // this.insert("", cx);
4676 // this.refresh_copilot_suggestions(true, cx);
4677 // });
4678 // }
4679
4680 // pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
4681 // self.transact(cx, |this, cx| {
4682 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4683 // let line_mode = s.line_mode;
4684 // s.move_with(|map, selection| {
4685 // if selection.is_empty() && !line_mode {
4686 // let cursor = movement::right(map, selection.head());
4687 // selection.end = cursor;
4688 // selection.reversed = true;
4689 // selection.goal = SelectionGoal::None;
4690 // }
4691 // })
4692 // });
4693 // this.insert("", cx);
4694 // this.refresh_copilot_suggestions(true, cx);
4695 // });
4696 // }
4697
4698 // pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
4699 // if self.move_to_prev_snippet_tabstop(cx) {
4700 // return;
4701 // }
4702
4703 // self.outdent(&Outdent, cx);
4704 // }
4705
4706 // pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
4707 // if self.move_to_next_snippet_tabstop(cx) {
4708 // return;
4709 // }
4710
4711 // let mut selections = self.selections.all_adjusted(cx);
4712 // let buffer = self.buffer.read(cx);
4713 // let snapshot = buffer.snapshot(cx);
4714 // let rows_iter = selections.iter().map(|s| s.head().row);
4715 // let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
4716
4717 // let mut edits = Vec::new();
4718 // let mut prev_edited_row = 0;
4719 // let mut row_delta = 0;
4720 // for selection in &mut selections {
4721 // if selection.start.row != prev_edited_row {
4722 // row_delta = 0;
4723 // }
4724 // prev_edited_row = selection.end.row;
4725
4726 // // If the selection is non-empty, then increase the indentation of the selected lines.
4727 // if !selection.is_empty() {
4728 // row_delta =
4729 // Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4730 // continue;
4731 // }
4732
4733 // // If the selection is empty and the cursor is in the leading whitespace before the
4734 // // suggested indentation, then auto-indent the line.
4735 // let cursor = selection.head();
4736 // let current_indent = snapshot.indent_size_for_line(cursor.row);
4737 // if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
4738 // if cursor.column < suggested_indent.len
4739 // && cursor.column <= current_indent.len
4740 // && current_indent.len <= suggested_indent.len
4741 // {
4742 // selection.start = Point::new(cursor.row, suggested_indent.len);
4743 // selection.end = selection.start;
4744 // if row_delta == 0 {
4745 // edits.extend(Buffer::edit_for_indent_size_adjustment(
4746 // cursor.row,
4747 // current_indent,
4748 // suggested_indent,
4749 // ));
4750 // row_delta = suggested_indent.len - current_indent.len;
4751 // }
4752 // continue;
4753 // }
4754 // }
4755
4756 // // Accept copilot suggestion if there is only one selection and the cursor is not
4757 // // in the leading whitespace.
4758 // if self.selections.count() == 1
4759 // && cursor.column >= current_indent.len
4760 // && self.has_active_copilot_suggestion(cx)
4761 // {
4762 // self.accept_copilot_suggestion(cx);
4763 // return;
4764 // }
4765
4766 // // Otherwise, insert a hard or soft tab.
4767 // let settings = buffer.settings_at(cursor, cx);
4768 // let tab_size = if settings.hard_tabs {
4769 // IndentSize::tab()
4770 // } else {
4771 // let tab_size = settings.tab_size.get();
4772 // let char_column = snapshot
4773 // .text_for_range(Point::new(cursor.row, 0)..cursor)
4774 // .flat_map(str::chars)
4775 // .count()
4776 // + row_delta as usize;
4777 // let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
4778 // IndentSize::spaces(chars_to_next_tab_stop)
4779 // };
4780 // selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
4781 // selection.end = selection.start;
4782 // edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
4783 // row_delta += tab_size.len;
4784 // }
4785
4786 // self.transact(cx, |this, cx| {
4787 // this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4788 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4789 // this.refresh_copilot_suggestions(true, cx);
4790 // });
4791 // }
4792
4793 // pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
4794 // let mut selections = self.selections.all::<Point>(cx);
4795 // let mut prev_edited_row = 0;
4796 // let mut row_delta = 0;
4797 // let mut edits = Vec::new();
4798 // let buffer = self.buffer.read(cx);
4799 // let snapshot = buffer.snapshot(cx);
4800 // for selection in &mut selections {
4801 // if selection.start.row != prev_edited_row {
4802 // row_delta = 0;
4803 // }
4804 // prev_edited_row = selection.end.row;
4805
4806 // row_delta =
4807 // Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4808 // }
4809
4810 // self.transact(cx, |this, cx| {
4811 // this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4812 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4813 // });
4814 // }
4815
4816 // fn indent_selection(
4817 // buffer: &MultiBuffer,
4818 // snapshot: &MultiBufferSnapshot,
4819 // selection: &mut Selection<Point>,
4820 // edits: &mut Vec<(Range<Point>, String)>,
4821 // delta_for_start_row: u32,
4822 // cx: &AppContext,
4823 // ) -> u32 {
4824 // let settings = buffer.settings_at(selection.start, cx);
4825 // let tab_size = settings.tab_size.get();
4826 // let indent_kind = if settings.hard_tabs {
4827 // IndentKind::Tab
4828 // } else {
4829 // IndentKind::Space
4830 // };
4831 // let mut start_row = selection.start.row;
4832 // let mut end_row = selection.end.row + 1;
4833
4834 // // If a selection ends at the beginning of a line, don't indent
4835 // // that last line.
4836 // if selection.end.column == 0 {
4837 // end_row -= 1;
4838 // }
4839
4840 // // Avoid re-indenting a row that has already been indented by a
4841 // // previous selection, but still update this selection's column
4842 // // to reflect that indentation.
4843 // if delta_for_start_row > 0 {
4844 // start_row += 1;
4845 // selection.start.column += delta_for_start_row;
4846 // if selection.end.row == selection.start.row {
4847 // selection.end.column += delta_for_start_row;
4848 // }
4849 // }
4850
4851 // let mut delta_for_end_row = 0;
4852 // for row in start_row..end_row {
4853 // let current_indent = snapshot.indent_size_for_line(row);
4854 // let indent_delta = match (current_indent.kind, indent_kind) {
4855 // (IndentKind::Space, IndentKind::Space) => {
4856 // let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
4857 // IndentSize::spaces(columns_to_next_tab_stop)
4858 // }
4859 // (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
4860 // (_, IndentKind::Tab) => IndentSize::tab(),
4861 // };
4862
4863 // let row_start = Point::new(row, 0);
4864 // edits.push((
4865 // row_start..row_start,
4866 // indent_delta.chars().collect::<String>(),
4867 // ));
4868
4869 // // Update this selection's endpoints to reflect the indentation.
4870 // if row == selection.start.row {
4871 // selection.start.column += indent_delta.len;
4872 // }
4873 // if row == selection.end.row {
4874 // selection.end.column += indent_delta.len;
4875 // delta_for_end_row = indent_delta.len;
4876 // }
4877 // }
4878
4879 // if selection.start.row == selection.end.row {
4880 // delta_for_start_row + delta_for_end_row
4881 // } else {
4882 // delta_for_end_row
4883 // }
4884 // }
4885
4886 // pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
4887 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4888 // let selections = self.selections.all::<Point>(cx);
4889 // let mut deletion_ranges = Vec::new();
4890 // let mut last_outdent = None;
4891 // {
4892 // let buffer = self.buffer.read(cx);
4893 // let snapshot = buffer.snapshot(cx);
4894 // for selection in &selections {
4895 // let settings = buffer.settings_at(selection.start, cx);
4896 // let tab_size = settings.tab_size.get();
4897 // let mut rows = selection.spanned_rows(false, &display_map);
4898
4899 // // Avoid re-outdenting a row that has already been outdented by a
4900 // // previous selection.
4901 // if let Some(last_row) = last_outdent {
4902 // if last_row == rows.start {
4903 // rows.start += 1;
4904 // }
4905 // }
4906
4907 // for row in rows {
4908 // let indent_size = snapshot.indent_size_for_line(row);
4909 // if indent_size.len > 0 {
4910 // let deletion_len = match indent_size.kind {
4911 // IndentKind::Space => {
4912 // let columns_to_prev_tab_stop = indent_size.len % tab_size;
4913 // if columns_to_prev_tab_stop == 0 {
4914 // tab_size
4915 // } else {
4916 // columns_to_prev_tab_stop
4917 // }
4918 // }
4919 // IndentKind::Tab => 1,
4920 // };
4921 // deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
4922 // last_outdent = Some(row);
4923 // }
4924 // }
4925 // }
4926 // }
4927
4928 // self.transact(cx, |this, cx| {
4929 // this.buffer.update(cx, |buffer, cx| {
4930 // let empty_str: Arc<str> = "".into();
4931 // buffer.edit(
4932 // deletion_ranges
4933 // .into_iter()
4934 // .map(|range| (range, empty_str.clone())),
4935 // None,
4936 // cx,
4937 // );
4938 // });
4939 // let selections = this.selections.all::<usize>(cx);
4940 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4941 // });
4942 // }
4943
4944 // pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
4945 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4946 // let selections = self.selections.all::<Point>(cx);
4947
4948 // let mut new_cursors = Vec::new();
4949 // let mut edit_ranges = Vec::new();
4950 // let mut selections = selections.iter().peekable();
4951 // while let Some(selection) = selections.next() {
4952 // let mut rows = selection.spanned_rows(false, &display_map);
4953 // let goal_display_column = selection.head().to_display_point(&display_map).column();
4954
4955 // // Accumulate contiguous regions of rows that we want to delete.
4956 // while let Some(next_selection) = selections.peek() {
4957 // let next_rows = next_selection.spanned_rows(false, &display_map);
4958 // if next_rows.start <= rows.end {
4959 // rows.end = next_rows.end;
4960 // selections.next().unwrap();
4961 // } else {
4962 // break;
4963 // }
4964 // }
4965
4966 // let buffer = &display_map.buffer_snapshot;
4967 // let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
4968 // let edit_end;
4969 // let cursor_buffer_row;
4970 // if buffer.max_point().row >= rows.end {
4971 // // If there's a line after the range, delete the \n from the end of the row range
4972 // // and position the cursor on the next line.
4973 // edit_end = Point::new(rows.end, 0).to_offset(buffer);
4974 // cursor_buffer_row = rows.end;
4975 // } else {
4976 // // If there isn't a line after the range, delete the \n from the line before the
4977 // // start of the row range and position the cursor there.
4978 // edit_start = edit_start.saturating_sub(1);
4979 // edit_end = buffer.len();
4980 // cursor_buffer_row = rows.start.saturating_sub(1);
4981 // }
4982
4983 // let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
4984 // *cursor.column_mut() =
4985 // cmp::min(goal_display_column, display_map.line_len(cursor.row()));
4986
4987 // new_cursors.push((
4988 // selection.id,
4989 // buffer.anchor_after(cursor.to_point(&display_map)),
4990 // ));
4991 // edit_ranges.push(edit_start..edit_end);
4992 // }
4993
4994 // self.transact(cx, |this, cx| {
4995 // let buffer = this.buffer.update(cx, |buffer, cx| {
4996 // let empty_str: Arc<str> = "".into();
4997 // buffer.edit(
4998 // edit_ranges
4999 // .into_iter()
5000 // .map(|range| (range, empty_str.clone())),
5001 // None,
5002 // cx,
5003 // );
5004 // buffer.snapshot(cx)
5005 // });
5006 // let new_selections = new_cursors
5007 // .into_iter()
5008 // .map(|(id, cursor)| {
5009 // let cursor = cursor.to_point(&buffer);
5010 // Selection {
5011 // id,
5012 // start: cursor,
5013 // end: cursor,
5014 // reversed: false,
5015 // goal: SelectionGoal::None,
5016 // }
5017 // })
5018 // .collect();
5019
5020 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5021 // s.select(new_selections);
5022 // });
5023 // });
5024 // }
5025
5026 // pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5027 // let mut row_ranges = Vec::<Range<u32>>::new();
5028 // for selection in self.selections.all::<Point>(cx) {
5029 // let start = selection.start.row;
5030 // let end = if selection.start.row == selection.end.row {
5031 // selection.start.row + 1
5032 // } else {
5033 // selection.end.row
5034 // };
5035
5036 // if let Some(last_row_range) = row_ranges.last_mut() {
5037 // if start <= last_row_range.end {
5038 // last_row_range.end = end;
5039 // continue;
5040 // }
5041 // }
5042 // row_ranges.push(start..end);
5043 // }
5044
5045 // let snapshot = self.buffer.read(cx).snapshot(cx);
5046 // let mut cursor_positions = Vec::new();
5047 // for row_range in &row_ranges {
5048 // let anchor = snapshot.anchor_before(Point::new(
5049 // row_range.end - 1,
5050 // snapshot.line_len(row_range.end - 1),
5051 // ));
5052 // cursor_positions.push(anchor.clone()..anchor);
5053 // }
5054
5055 // self.transact(cx, |this, cx| {
5056 // for row_range in row_ranges.into_iter().rev() {
5057 // for row in row_range.rev() {
5058 // let end_of_line = Point::new(row, snapshot.line_len(row));
5059 // let indent = snapshot.indent_size_for_line(row + 1);
5060 // let start_of_next_line = Point::new(row + 1, indent.len);
5061
5062 // let replace = if snapshot.line_len(row + 1) > indent.len {
5063 // " "
5064 // } else {
5065 // ""
5066 // };
5067
5068 // this.buffer.update(cx, |buffer, cx| {
5069 // buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5070 // });
5071 // }
5072 // }
5073
5074 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5075 // s.select_anchor_ranges(cursor_positions)
5076 // });
5077 // });
5078 // }
5079
5080 // pub fn sort_lines_case_sensitive(
5081 // &mut self,
5082 // _: &SortLinesCaseSensitive,
5083 // cx: &mut ViewContext<Self>,
5084 // ) {
5085 // self.manipulate_lines(cx, |lines| lines.sort())
5086 // }
5087
5088 // pub fn sort_lines_case_insensitive(
5089 // &mut self,
5090 // _: &SortLinesCaseInsensitive,
5091 // cx: &mut ViewContext<Self>,
5092 // ) {
5093 // self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5094 // }
5095
5096 // pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5097 // self.manipulate_lines(cx, |lines| lines.reverse())
5098 // }
5099
5100 // pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5101 // self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5102 // }
5103
5104 // fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5105 // where
5106 // Fn: FnMut(&mut [&str]),
5107 // {
5108 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5109 // let buffer = self.buffer.read(cx).snapshot(cx);
5110
5111 // let mut edits = Vec::new();
5112
5113 // let selections = self.selections.all::<Point>(cx);
5114 // let mut selections = selections.iter().peekable();
5115 // let mut contiguous_row_selections = Vec::new();
5116 // let mut new_selections = Vec::new();
5117
5118 // while let Some(selection) = selections.next() {
5119 // let (start_row, end_row) = consume_contiguous_rows(
5120 // &mut contiguous_row_selections,
5121 // selection,
5122 // &display_map,
5123 // &mut selections,
5124 // );
5125
5126 // let start_point = Point::new(start_row, 0);
5127 // let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
5128 // let text = buffer
5129 // .text_for_range(start_point..end_point)
5130 // .collect::<String>();
5131 // let mut lines = text.split("\n").collect_vec();
5132
5133 // let lines_len = lines.len();
5134 // callback(&mut lines);
5135
5136 // // This is a current limitation with selections.
5137 // // If we wanted to support removing or adding lines, we'd need to fix the logic associated with selections.
5138 // debug_assert!(
5139 // lines.len() == lines_len,
5140 // "callback should not change the number of lines"
5141 // );
5142
5143 // edits.push((start_point..end_point, lines.join("\n")));
5144 // let start_anchor = buffer.anchor_after(start_point);
5145 // let end_anchor = buffer.anchor_before(end_point);
5146
5147 // // Make selection and push
5148 // new_selections.push(Selection {
5149 // id: selection.id,
5150 // start: start_anchor.to_offset(&buffer),
5151 // end: end_anchor.to_offset(&buffer),
5152 // goal: SelectionGoal::None,
5153 // reversed: selection.reversed,
5154 // });
5155 // }
5156
5157 // self.transact(cx, |this, cx| {
5158 // this.buffer.update(cx, |buffer, cx| {
5159 // buffer.edit(edits, None, cx);
5160 // });
5161
5162 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5163 // s.select(new_selections);
5164 // });
5165
5166 // this.request_autoscroll(Autoscroll::fit(), cx);
5167 // });
5168 // }
5169
5170 // pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5171 // self.manipulate_text(cx, |text| text.to_uppercase())
5172 // }
5173
5174 // pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5175 // self.manipulate_text(cx, |text| text.to_lowercase())
5176 // }
5177
5178 // pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
5179 // self.manipulate_text(cx, |text| {
5180 // // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5181 // // https://github.com/rutrum/convert-case/issues/16
5182 // text.split("\n")
5183 // .map(|line| line.to_case(Case::Title))
5184 // .join("\n")
5185 // })
5186 // }
5187
5188 // pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
5189 // self.manipulate_text(cx, |text| text.to_case(Case::Snake))
5190 // }
5191
5192 // pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
5193 // self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
5194 // }
5195
5196 // pub fn convert_to_upper_camel_case(
5197 // &mut self,
5198 // _: &ConvertToUpperCamelCase,
5199 // cx: &mut ViewContext<Self>,
5200 // ) {
5201 // self.manipulate_text(cx, |text| {
5202 // // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5203 // // https://github.com/rutrum/convert-case/issues/16
5204 // text.split("\n")
5205 // .map(|line| line.to_case(Case::UpperCamel))
5206 // .join("\n")
5207 // })
5208 // }
5209
5210 // pub fn convert_to_lower_camel_case(
5211 // &mut self,
5212 // _: &ConvertToLowerCamelCase,
5213 // cx: &mut ViewContext<Self>,
5214 // ) {
5215 // self.manipulate_text(cx, |text| text.to_case(Case::Camel))
5216 // }
5217
5218 // fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5219 // where
5220 // Fn: FnMut(&str) -> String,
5221 // {
5222 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5223 // let buffer = self.buffer.read(cx).snapshot(cx);
5224
5225 // let mut new_selections = Vec::new();
5226 // let mut edits = Vec::new();
5227 // let mut selection_adjustment = 0i32;
5228
5229 // for selection in self.selections.all::<usize>(cx) {
5230 // let selection_is_empty = selection.is_empty();
5231
5232 // let (start, end) = if selection_is_empty {
5233 // let word_range = movement::surrounding_word(
5234 // &display_map,
5235 // selection.start.to_display_point(&display_map),
5236 // );
5237 // let start = word_range.start.to_offset(&display_map, Bias::Left);
5238 // let end = word_range.end.to_offset(&display_map, Bias::Left);
5239 // (start, end)
5240 // } else {
5241 // (selection.start, selection.end)
5242 // };
5243
5244 // let text = buffer.text_for_range(start..end).collect::<String>();
5245 // let old_length = text.len() as i32;
5246 // let text = callback(&text);
5247
5248 // new_selections.push(Selection {
5249 // start: (start as i32 - selection_adjustment) as usize,
5250 // end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5251 // goal: SelectionGoal::None,
5252 // ..selection
5253 // });
5254
5255 // selection_adjustment += old_length - text.len() as i32;
5256
5257 // edits.push((start..end, text));
5258 // }
5259
5260 // self.transact(cx, |this, cx| {
5261 // this.buffer.update(cx, |buffer, cx| {
5262 // buffer.edit(edits, None, cx);
5263 // });
5264
5265 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5266 // s.select(new_selections);
5267 // });
5268
5269 // this.request_autoscroll(Autoscroll::fit(), cx);
5270 // });
5271 // }
5272
5273 // pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
5274 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5275 // let buffer = &display_map.buffer_snapshot;
5276 // let selections = self.selections.all::<Point>(cx);
5277
5278 // let mut edits = Vec::new();
5279 // let mut selections_iter = selections.iter().peekable();
5280 // while let Some(selection) = selections_iter.next() {
5281 // // Avoid duplicating the same lines twice.
5282 // let mut rows = selection.spanned_rows(false, &display_map);
5283
5284 // while let Some(next_selection) = selections_iter.peek() {
5285 // let next_rows = next_selection.spanned_rows(false, &display_map);
5286 // if next_rows.start < rows.end {
5287 // rows.end = next_rows.end;
5288 // selections_iter.next().unwrap();
5289 // } else {
5290 // break;
5291 // }
5292 // }
5293
5294 // // Copy the text from the selected row region and splice it at the start of the region.
5295 // let start = Point::new(rows.start, 0);
5296 // let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
5297 // let text = buffer
5298 // .text_for_range(start..end)
5299 // .chain(Some("\n"))
5300 // .collect::<String>();
5301 // edits.push((start..start, text));
5302 // }
5303
5304 // self.transact(cx, |this, cx| {
5305 // this.buffer.update(cx, |buffer, cx| {
5306 // buffer.edit(edits, None, cx);
5307 // });
5308
5309 // this.request_autoscroll(Autoscroll::fit(), cx);
5310 // });
5311 // }
5312
5313 // pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5314 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5315 // let buffer = self.buffer.read(cx).snapshot(cx);
5316
5317 // let mut edits = Vec::new();
5318 // let mut unfold_ranges = Vec::new();
5319 // let mut refold_ranges = Vec::new();
5320
5321 // let selections = self.selections.all::<Point>(cx);
5322 // let mut selections = selections.iter().peekable();
5323 // let mut contiguous_row_selections = Vec::new();
5324 // let mut new_selections = Vec::new();
5325
5326 // while let Some(selection) = selections.next() {
5327 // // Find all the selections that span a contiguous row range
5328 // let (start_row, end_row) = consume_contiguous_rows(
5329 // &mut contiguous_row_selections,
5330 // selection,
5331 // &display_map,
5332 // &mut selections,
5333 // );
5334
5335 // // Move the text spanned by the row range to be before the line preceding the row range
5336 // if start_row > 0 {
5337 // let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
5338 // ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
5339 // let insertion_point = display_map
5340 // .prev_line_boundary(Point::new(start_row - 1, 0))
5341 // .0;
5342
5343 // // Don't move lines across excerpts
5344 // if buffer
5345 // .excerpt_boundaries_in_range((
5346 // Bound::Excluded(insertion_point),
5347 // Bound::Included(range_to_move.end),
5348 // ))
5349 // .next()
5350 // .is_none()
5351 // {
5352 // let text = buffer
5353 // .text_for_range(range_to_move.clone())
5354 // .flat_map(|s| s.chars())
5355 // .skip(1)
5356 // .chain(['\n'])
5357 // .collect::<String>();
5358
5359 // edits.push((
5360 // buffer.anchor_after(range_to_move.start)
5361 // ..buffer.anchor_before(range_to_move.end),
5362 // String::new(),
5363 // ));
5364 // let insertion_anchor = buffer.anchor_after(insertion_point);
5365 // edits.push((insertion_anchor..insertion_anchor, text));
5366
5367 // let row_delta = range_to_move.start.row - insertion_point.row + 1;
5368
5369 // // Move selections up
5370 // new_selections.extend(contiguous_row_selections.drain(..).map(
5371 // |mut selection| {
5372 // selection.start.row -= row_delta;
5373 // selection.end.row -= row_delta;
5374 // selection
5375 // },
5376 // ));
5377
5378 // // Move folds up
5379 // unfold_ranges.push(range_to_move.clone());
5380 // for fold in display_map.folds_in_range(
5381 // buffer.anchor_before(range_to_move.start)
5382 // ..buffer.anchor_after(range_to_move.end),
5383 // ) {
5384 // let mut start = fold.start.to_point(&buffer);
5385 // let mut end = fold.end.to_point(&buffer);
5386 // start.row -= row_delta;
5387 // end.row -= row_delta;
5388 // refold_ranges.push(start..end);
5389 // }
5390 // }
5391 // }
5392
5393 // // If we didn't move line(s), preserve the existing selections
5394 // new_selections.append(&mut contiguous_row_selections);
5395 // }
5396
5397 // self.transact(cx, |this, cx| {
5398 // this.unfold_ranges(unfold_ranges, true, true, cx);
5399 // this.buffer.update(cx, |buffer, cx| {
5400 // for (range, text) in edits {
5401 // buffer.edit([(range, text)], None, cx);
5402 // }
5403 // });
5404 // this.fold_ranges(refold_ranges, true, cx);
5405 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5406 // s.select(new_selections);
5407 // })
5408 // });
5409 // }
5410
5411 // pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5412 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5413 // let buffer = self.buffer.read(cx).snapshot(cx);
5414
5415 // let mut edits = Vec::new();
5416 // let mut unfold_ranges = Vec::new();
5417 // let mut refold_ranges = Vec::new();
5418
5419 // let selections = self.selections.all::<Point>(cx);
5420 // let mut selections = selections.iter().peekable();
5421 // let mut contiguous_row_selections = Vec::new();
5422 // let mut new_selections = Vec::new();
5423
5424 // while let Some(selection) = selections.next() {
5425 // // Find all the selections that span a contiguous row range
5426 // let (start_row, end_row) = consume_contiguous_rows(
5427 // &mut contiguous_row_selections,
5428 // selection,
5429 // &display_map,
5430 // &mut selections,
5431 // );
5432
5433 // // Move the text spanned by the row range to be after the last line of the row range
5434 // if end_row <= buffer.max_point().row {
5435 // let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5436 // let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5437
5438 // // Don't move lines across excerpt boundaries
5439 // if buffer
5440 // .excerpt_boundaries_in_range((
5441 // Bound::Excluded(range_to_move.start),
5442 // Bound::Included(insertion_point),
5443 // ))
5444 // .next()
5445 // .is_none()
5446 // {
5447 // let mut text = String::from("\n");
5448 // text.extend(buffer.text_for_range(range_to_move.clone()));
5449 // text.pop(); // Drop trailing newline
5450 // edits.push((
5451 // buffer.anchor_after(range_to_move.start)
5452 // ..buffer.anchor_before(range_to_move.end),
5453 // String::new(),
5454 // ));
5455 // let insertion_anchor = buffer.anchor_after(insertion_point);
5456 // edits.push((insertion_anchor..insertion_anchor, text));
5457
5458 // let row_delta = insertion_point.row - range_to_move.end.row + 1;
5459
5460 // // Move selections down
5461 // new_selections.extend(contiguous_row_selections.drain(..).map(
5462 // |mut selection| {
5463 // selection.start.row += row_delta;
5464 // selection.end.row += row_delta;
5465 // selection
5466 // },
5467 // ));
5468
5469 // // Move folds down
5470 // unfold_ranges.push(range_to_move.clone());
5471 // for fold in display_map.folds_in_range(
5472 // buffer.anchor_before(range_to_move.start)
5473 // ..buffer.anchor_after(range_to_move.end),
5474 // ) {
5475 // let mut start = fold.start.to_point(&buffer);
5476 // let mut end = fold.end.to_point(&buffer);
5477 // start.row += row_delta;
5478 // end.row += row_delta;
5479 // refold_ranges.push(start..end);
5480 // }
5481 // }
5482 // }
5483
5484 // // If we didn't move line(s), preserve the existing selections
5485 // new_selections.append(&mut contiguous_row_selections);
5486 // }
5487
5488 // self.transact(cx, |this, cx| {
5489 // this.unfold_ranges(unfold_ranges, true, true, cx);
5490 // this.buffer.update(cx, |buffer, cx| {
5491 // for (range, text) in edits {
5492 // buffer.edit([(range, text)], None, cx);
5493 // }
5494 // });
5495 // this.fold_ranges(refold_ranges, true, cx);
5496 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5497 // });
5498 // }
5499
5500 // pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5501 // let text_layout_details = &self.text_layout_details(cx);
5502 // self.transact(cx, |this, cx| {
5503 // let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5504 // let mut edits: Vec<(Range<usize>, String)> = Default::default();
5505 // let line_mode = s.line_mode;
5506 // s.move_with(|display_map, selection| {
5507 // if !selection.is_empty() || line_mode {
5508 // return;
5509 // }
5510
5511 // let mut head = selection.head();
5512 // let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5513 // if head.column() == display_map.line_len(head.row()) {
5514 // transpose_offset = display_map
5515 // .buffer_snapshot
5516 // .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5517 // }
5518
5519 // if transpose_offset == 0 {
5520 // return;
5521 // }
5522
5523 // *head.column_mut() += 1;
5524 // head = display_map.clip_point(head, Bias::Right);
5525 // let goal = SelectionGoal::HorizontalPosition(
5526 // display_map.x_for_point(head, &text_layout_details),
5527 // );
5528 // selection.collapse_to(head, goal);
5529
5530 // let transpose_start = display_map
5531 // .buffer_snapshot
5532 // .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5533 // if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5534 // let transpose_end = display_map
5535 // .buffer_snapshot
5536 // .clip_offset(transpose_offset + 1, Bias::Right);
5537 // if let Some(ch) =
5538 // display_map.buffer_snapshot.chars_at(transpose_start).next()
5539 // {
5540 // edits.push((transpose_start..transpose_offset, String::new()));
5541 // edits.push((transpose_end..transpose_end, ch.to_string()));
5542 // }
5543 // }
5544 // });
5545 // edits
5546 // });
5547 // this.buffer
5548 // .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5549 // let selections = this.selections.all::<usize>(cx);
5550 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5551 // s.select(selections);
5552 // });
5553 // });
5554 // }
5555
5556 // pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5557 // let mut text = String::new();
5558 // let buffer = self.buffer.read(cx).snapshot(cx);
5559 // let mut selections = self.selections.all::<Point>(cx);
5560 // let mut clipboard_selections = Vec::with_capacity(selections.len());
5561 // {
5562 // let max_point = buffer.max_point();
5563 // let mut is_first = true;
5564 // for selection in &mut selections {
5565 // let is_entire_line = selection.is_empty() || self.selections.line_mode;
5566 // if is_entire_line {
5567 // selection.start = Point::new(selection.start.row, 0);
5568 // selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5569 // selection.goal = SelectionGoal::None;
5570 // }
5571 // if is_first {
5572 // is_first = false;
5573 // } else {
5574 // text += "\n";
5575 // }
5576 // let mut len = 0;
5577 // for chunk in buffer.text_for_range(selection.start..selection.end) {
5578 // text.push_str(chunk);
5579 // len += chunk.len();
5580 // }
5581 // clipboard_selections.push(ClipboardSelection {
5582 // len,
5583 // is_entire_line,
5584 // first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5585 // });
5586 // }
5587 // }
5588
5589 // self.transact(cx, |this, cx| {
5590 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5591 // s.select(selections);
5592 // });
5593 // this.insert("", cx);
5594 // cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5595 // });
5596 // }
5597
5598 // pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5599 // let selections = self.selections.all::<Point>(cx);
5600 // let buffer = self.buffer.read(cx).read(cx);
5601 // let mut text = String::new();
5602
5603 // let mut clipboard_selections = Vec::with_capacity(selections.len());
5604 // {
5605 // let max_point = buffer.max_point();
5606 // let mut is_first = true;
5607 // for selection in selections.iter() {
5608 // let mut start = selection.start;
5609 // let mut end = selection.end;
5610 // let is_entire_line = selection.is_empty() || self.selections.line_mode;
5611 // if is_entire_line {
5612 // start = Point::new(start.row, 0);
5613 // end = cmp::min(max_point, Point::new(end.row + 1, 0));
5614 // }
5615 // if is_first {
5616 // is_first = false;
5617 // } else {
5618 // text += "\n";
5619 // }
5620 // let mut len = 0;
5621 // for chunk in buffer.text_for_range(start..end) {
5622 // text.push_str(chunk);
5623 // len += chunk.len();
5624 // }
5625 // clipboard_selections.push(ClipboardSelection {
5626 // len,
5627 // is_entire_line,
5628 // first_line_indent: buffer.indent_size_for_line(start.row).len,
5629 // });
5630 // }
5631 // }
5632
5633 // cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5634 // }
5635
5636 // pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5637 // self.transact(cx, |this, cx| {
5638 // if let Some(item) = cx.read_from_clipboard() {
5639 // let clipboard_text = Cow::Borrowed(item.text());
5640 // if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5641 // let old_selections = this.selections.all::<usize>(cx);
5642 // let all_selections_were_entire_line =
5643 // clipboard_selections.iter().all(|s| s.is_entire_line);
5644 // let first_selection_indent_column =
5645 // clipboard_selections.first().map(|s| s.first_line_indent);
5646 // if clipboard_selections.len() != old_selections.len() {
5647 // clipboard_selections.drain(..);
5648 // }
5649
5650 // this.buffer.update(cx, |buffer, cx| {
5651 // let snapshot = buffer.read(cx);
5652 // let mut start_offset = 0;
5653 // let mut edits = Vec::new();
5654 // let mut original_indent_columns = Vec::new();
5655 // let line_mode = this.selections.line_mode;
5656 // for (ix, selection) in old_selections.iter().enumerate() {
5657 // let to_insert;
5658 // let entire_line;
5659 // let original_indent_column;
5660 // if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5661 // let end_offset = start_offset + clipboard_selection.len;
5662 // to_insert = &clipboard_text[start_offset..end_offset];
5663 // entire_line = clipboard_selection.is_entire_line;
5664 // start_offset = end_offset + 1;
5665 // original_indent_column =
5666 // Some(clipboard_selection.first_line_indent);
5667 // } else {
5668 // to_insert = clipboard_text.as_str();
5669 // entire_line = all_selections_were_entire_line;
5670 // original_indent_column = first_selection_indent_column
5671 // }
5672
5673 // // If the corresponding selection was empty when this slice of the
5674 // // clipboard text was written, then the entire line containing the
5675 // // selection was copied. If this selection is also currently empty,
5676 // // then paste the line before the current line of the buffer.
5677 // let range = if selection.is_empty() && !line_mode && entire_line {
5678 // let column = selection.start.to_point(&snapshot).column as usize;
5679 // let line_start = selection.start - column;
5680 // line_start..line_start
5681 // } else {
5682 // selection.range()
5683 // };
5684
5685 // edits.push((range, to_insert));
5686 // original_indent_columns.extend(original_indent_column);
5687 // }
5688 // drop(snapshot);
5689
5690 // buffer.edit(
5691 // edits,
5692 // Some(AutoindentMode::Block {
5693 // original_indent_columns,
5694 // }),
5695 // cx,
5696 // );
5697 // });
5698
5699 // let selections = this.selections.all::<usize>(cx);
5700 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5701 // } else {
5702 // this.insert(&clipboard_text, cx);
5703 // }
5704 // }
5705 // });
5706 // }
5707
5708 // pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5709 // if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5710 // if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5711 // self.change_selections(None, cx, |s| {
5712 // s.select_anchors(selections.to_vec());
5713 // });
5714 // }
5715 // self.request_autoscroll(Autoscroll::fit(), cx);
5716 // self.unmark_text(cx);
5717 // self.refresh_copilot_suggestions(true, cx);
5718 // cx.emit(Event::Edited);
5719 // }
5720 // }
5721
5722 // pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5723 // if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5724 // if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5725 // {
5726 // self.change_selections(None, cx, |s| {
5727 // s.select_anchors(selections.to_vec());
5728 // });
5729 // }
5730 // self.request_autoscroll(Autoscroll::fit(), cx);
5731 // self.unmark_text(cx);
5732 // self.refresh_copilot_suggestions(true, cx);
5733 // cx.emit(Event::Edited);
5734 // }
5735 // }
5736
5737 // pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5738 // self.buffer
5739 // .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5740 // }
5741
5742 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5743 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5744 let line_mode = s.line_mode;
5745 s.move_with(|map, selection| {
5746 let cursor = if selection.is_empty() && !line_mode {
5747 movement::left(map, selection.start)
5748 } else {
5749 selection.start
5750 };
5751 selection.collapse_to(cursor, SelectionGoal::None);
5752 });
5753 })
5754 }
5755
5756 // pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5757 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5758 // s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5759 // })
5760 // }
5761
5762 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5763 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5764 let line_mode = s.line_mode;
5765 s.move_with(|map, selection| {
5766 let cursor = if selection.is_empty() && !line_mode {
5767 movement::right(map, selection.end)
5768 } else {
5769 selection.end
5770 };
5771 selection.collapse_to(cursor, SelectionGoal::None)
5772 });
5773 })
5774 }
5775
5776 // pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5777 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5778 // s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5779 // })
5780 // }
5781
5782 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5783 if self.take_rename(true, cx).is_some() {
5784 return;
5785 }
5786
5787 if matches!(self.mode, EditorMode::SingleLine) {
5788 cx.propagate();
5789 return;
5790 }
5791
5792 let text_layout_details = &self.text_layout_details(cx);
5793
5794 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5795 let line_mode = s.line_mode;
5796 s.move_with(|map, selection| {
5797 if !selection.is_empty() && !line_mode {
5798 selection.goal = SelectionGoal::None;
5799 }
5800 let (cursor, goal) = movement::up(
5801 map,
5802 selection.start,
5803 selection.goal,
5804 false,
5805 &text_layout_details,
5806 );
5807 selection.collapse_to(cursor, goal);
5808 });
5809 })
5810 }
5811
5812 // pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5813 // if self.take_rename(true, cx).is_some() {
5814 // return;
5815 // }
5816
5817 // if matches!(self.mode, EditorMode::SingleLine) {
5818 // cx.propagate();
5819 // return;
5820 // }
5821
5822 // let row_count = if let Some(row_count) = self.visible_line_count() {
5823 // row_count as u32 - 1
5824 // } else {
5825 // return;
5826 // };
5827
5828 // let autoscroll = if action.center_cursor {
5829 // Autoscroll::center()
5830 // } else {
5831 // Autoscroll::fit()
5832 // };
5833
5834 // let text_layout_details = &self.text_layout_details(cx);
5835
5836 // self.change_selections(Some(autoscroll), cx, |s| {
5837 // let line_mode = s.line_mode;
5838 // s.move_with(|map, selection| {
5839 // if !selection.is_empty() && !line_mode {
5840 // selection.goal = SelectionGoal::None;
5841 // }
5842 // let (cursor, goal) = movement::up_by_rows(
5843 // map,
5844 // selection.end,
5845 // row_count,
5846 // selection.goal,
5847 // false,
5848 // &text_layout_details,
5849 // );
5850 // selection.collapse_to(cursor, goal);
5851 // });
5852 // });
5853 // }
5854
5855 // pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5856 // let text_layout_details = &self.text_layout_details(cx);
5857 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5858 // s.move_heads_with(|map, head, goal| {
5859 // movement::up(map, head, goal, false, &text_layout_details)
5860 // })
5861 // })
5862 // }
5863
5864 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5865 dbg!("move_down");
5866 self.take_rename(true, cx);
5867
5868 if self.mode == EditorMode::SingleLine {
5869 cx.propagate();
5870 return;
5871 }
5872
5873 let text_layout_details = &self.text_layout_details(cx);
5874 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5875 let line_mode = s.line_mode;
5876 s.move_with(|map, selection| {
5877 if !selection.is_empty() && !line_mode {
5878 selection.goal = SelectionGoal::None;
5879 }
5880 let (cursor, goal) = movement::down(
5881 map,
5882 selection.end,
5883 selection.goal,
5884 false,
5885 &text_layout_details,
5886 );
5887 selection.collapse_to(cursor, goal);
5888 });
5889 });
5890 }
5891
5892 // pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5893 // if self.take_rename(true, cx).is_some() {
5894 // return;
5895 // }
5896
5897 // if self
5898 // .context_menu
5899 // .write()
5900 // .as_mut()
5901 // .map(|menu| menu.select_last(self.project.as_ref(), cx))
5902 // .unwrap_or(false)
5903 // {
5904 // return;
5905 // }
5906
5907 // if matches!(self.mode, EditorMode::SingleLine) {
5908 // cx.propagate();
5909 // return;
5910 // }
5911
5912 // let row_count = if let Some(row_count) = self.visible_line_count() {
5913 // row_count as u32 - 1
5914 // } else {
5915 // return;
5916 // };
5917
5918 // let autoscroll = if action.center_cursor {
5919 // Autoscroll::center()
5920 // } else {
5921 // Autoscroll::fit()
5922 // };
5923
5924 // let text_layout_details = &self.text_layout_details(cx);
5925 // self.change_selections(Some(autoscroll), cx, |s| {
5926 // let line_mode = s.line_mode;
5927 // s.move_with(|map, selection| {
5928 // if !selection.is_empty() && !line_mode {
5929 // selection.goal = SelectionGoal::None;
5930 // }
5931 // let (cursor, goal) = movement::down_by_rows(
5932 // map,
5933 // selection.end,
5934 // row_count,
5935 // selection.goal,
5936 // false,
5937 // &text_layout_details,
5938 // );
5939 // selection.collapse_to(cursor, goal);
5940 // });
5941 // });
5942 // }
5943
5944 // pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
5945 // let text_layout_details = &self.text_layout_details(cx);
5946 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5947 // s.move_heads_with(|map, head, goal| {
5948 // movement::down(map, head, goal, false, &text_layout_details)
5949 // })
5950 // });
5951 // }
5952
5953 // pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
5954 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5955 // context_menu.select_first(self.project.as_ref(), cx);
5956 // }
5957 // }
5958
5959 // pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
5960 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5961 // context_menu.select_prev(self.project.as_ref(), cx);
5962 // }
5963 // }
5964
5965 // pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
5966 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5967 // context_menu.select_next(self.project.as_ref(), cx);
5968 // }
5969 // }
5970
5971 // pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
5972 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5973 // context_menu.select_last(self.project.as_ref(), cx);
5974 // }
5975 // }
5976
5977 // pub fn move_to_previous_word_start(
5978 // &mut self,
5979 // _: &MoveToPreviousWordStart,
5980 // cx: &mut ViewContext<Self>,
5981 // ) {
5982 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5983 // s.move_cursors_with(|map, head, _| {
5984 // (
5985 // movement::previous_word_start(map, head),
5986 // SelectionGoal::None,
5987 // )
5988 // });
5989 // })
5990 // }
5991
5992 // pub fn move_to_previous_subword_start(
5993 // &mut self,
5994 // _: &MoveToPreviousSubwordStart,
5995 // cx: &mut ViewContext<Self>,
5996 // ) {
5997 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5998 // s.move_cursors_with(|map, head, _| {
5999 // (
6000 // movement::previous_subword_start(map, head),
6001 // SelectionGoal::None,
6002 // )
6003 // });
6004 // })
6005 // }
6006
6007 // pub fn select_to_previous_word_start(
6008 // &mut self,
6009 // _: &SelectToPreviousWordStart,
6010 // cx: &mut ViewContext<Self>,
6011 // ) {
6012 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6013 // s.move_heads_with(|map, head, _| {
6014 // (
6015 // movement::previous_word_start(map, head),
6016 // SelectionGoal::None,
6017 // )
6018 // });
6019 // })
6020 // }
6021
6022 // pub fn select_to_previous_subword_start(
6023 // &mut self,
6024 // _: &SelectToPreviousSubwordStart,
6025 // cx: &mut ViewContext<Self>,
6026 // ) {
6027 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6028 // s.move_heads_with(|map, head, _| {
6029 // (
6030 // movement::previous_subword_start(map, head),
6031 // SelectionGoal::None,
6032 // )
6033 // });
6034 // })
6035 // }
6036
6037 // pub fn delete_to_previous_word_start(
6038 // &mut self,
6039 // _: &DeleteToPreviousWordStart,
6040 // cx: &mut ViewContext<Self>,
6041 // ) {
6042 // self.transact(cx, |this, cx| {
6043 // this.select_autoclose_pair(cx);
6044 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6045 // let line_mode = s.line_mode;
6046 // s.move_with(|map, selection| {
6047 // if selection.is_empty() && !line_mode {
6048 // let cursor = movement::previous_word_start(map, selection.head());
6049 // selection.set_head(cursor, SelectionGoal::None);
6050 // }
6051 // });
6052 // });
6053 // this.insert("", cx);
6054 // });
6055 // }
6056
6057 // pub fn delete_to_previous_subword_start(
6058 // &mut self,
6059 // _: &DeleteToPreviousSubwordStart,
6060 // cx: &mut ViewContext<Self>,
6061 // ) {
6062 // self.transact(cx, |this, cx| {
6063 // this.select_autoclose_pair(cx);
6064 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6065 // let line_mode = s.line_mode;
6066 // s.move_with(|map, selection| {
6067 // if selection.is_empty() && !line_mode {
6068 // let cursor = movement::previous_subword_start(map, selection.head());
6069 // selection.set_head(cursor, SelectionGoal::None);
6070 // }
6071 // });
6072 // });
6073 // this.insert("", cx);
6074 // });
6075 // }
6076
6077 // pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6078 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6079 // s.move_cursors_with(|map, head, _| {
6080 // (movement::next_word_end(map, head), SelectionGoal::None)
6081 // });
6082 // })
6083 // }
6084
6085 // pub fn move_to_next_subword_end(
6086 // &mut self,
6087 // _: &MoveToNextSubwordEnd,
6088 // cx: &mut ViewContext<Self>,
6089 // ) {
6090 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6091 // s.move_cursors_with(|map, head, _| {
6092 // (movement::next_subword_end(map, head), SelectionGoal::None)
6093 // });
6094 // })
6095 // }
6096
6097 // pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
6098 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6099 // s.move_heads_with(|map, head, _| {
6100 // (movement::next_word_end(map, head), SelectionGoal::None)
6101 // });
6102 // })
6103 // }
6104
6105 // pub fn select_to_next_subword_end(
6106 // &mut self,
6107 // _: &SelectToNextSubwordEnd,
6108 // cx: &mut ViewContext<Self>,
6109 // ) {
6110 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6111 // s.move_heads_with(|map, head, _| {
6112 // (movement::next_subword_end(map, head), SelectionGoal::None)
6113 // });
6114 // })
6115 // }
6116
6117 // pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
6118 // self.transact(cx, |this, cx| {
6119 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6120 // let line_mode = s.line_mode;
6121 // s.move_with(|map, selection| {
6122 // if selection.is_empty() && !line_mode {
6123 // let cursor = movement::next_word_end(map, selection.head());
6124 // selection.set_head(cursor, SelectionGoal::None);
6125 // }
6126 // });
6127 // });
6128 // this.insert("", cx);
6129 // });
6130 // }
6131
6132 // pub fn delete_to_next_subword_end(
6133 // &mut self,
6134 // _: &DeleteToNextSubwordEnd,
6135 // cx: &mut ViewContext<Self>,
6136 // ) {
6137 // self.transact(cx, |this, cx| {
6138 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6139 // s.move_with(|map, selection| {
6140 // if selection.is_empty() {
6141 // let cursor = movement::next_subword_end(map, selection.head());
6142 // selection.set_head(cursor, SelectionGoal::None);
6143 // }
6144 // });
6145 // });
6146 // this.insert("", cx);
6147 // });
6148 // }
6149
6150 // pub fn move_to_beginning_of_line(
6151 // &mut self,
6152 // _: &MoveToBeginningOfLine,
6153 // cx: &mut ViewContext<Self>,
6154 // ) {
6155 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6156 // s.move_cursors_with(|map, head, _| {
6157 // (
6158 // movement::indented_line_beginning(map, head, true),
6159 // SelectionGoal::None,
6160 // )
6161 // });
6162 // })
6163 // }
6164
6165 // pub fn select_to_beginning_of_line(
6166 // &mut self,
6167 // action: &SelectToBeginningOfLine,
6168 // cx: &mut ViewContext<Self>,
6169 // ) {
6170 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6171 // s.move_heads_with(|map, head, _| {
6172 // (
6173 // movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6174 // SelectionGoal::None,
6175 // )
6176 // });
6177 // });
6178 // }
6179
6180 // pub fn delete_to_beginning_of_line(
6181 // &mut self,
6182 // _: &DeleteToBeginningOfLine,
6183 // cx: &mut ViewContext<Self>,
6184 // ) {
6185 // self.transact(cx, |this, cx| {
6186 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6187 // s.move_with(|_, selection| {
6188 // selection.reversed = true;
6189 // });
6190 // });
6191
6192 // this.select_to_beginning_of_line(
6193 // &SelectToBeginningOfLine {
6194 // stop_at_soft_wraps: false,
6195 // },
6196 // cx,
6197 // );
6198 // this.backspace(&Backspace, cx);
6199 // });
6200 // }
6201
6202 // pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6203 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6204 // s.move_cursors_with(|map, head, _| {
6205 // (movement::line_end(map, head, true), SelectionGoal::None)
6206 // });
6207 // })
6208 // }
6209
6210 // pub fn select_to_end_of_line(
6211 // &mut self,
6212 // action: &SelectToEndOfLine,
6213 // cx: &mut ViewContext<Self>,
6214 // ) {
6215 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6216 // s.move_heads_with(|map, head, _| {
6217 // (
6218 // movement::line_end(map, head, action.stop_at_soft_wraps),
6219 // SelectionGoal::None,
6220 // )
6221 // });
6222 // })
6223 // }
6224
6225 // pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6226 // self.transact(cx, |this, cx| {
6227 // this.select_to_end_of_line(
6228 // &SelectToEndOfLine {
6229 // stop_at_soft_wraps: false,
6230 // },
6231 // cx,
6232 // );
6233 // this.delete(&Delete, cx);
6234 // });
6235 // }
6236
6237 // pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6238 // self.transact(cx, |this, cx| {
6239 // this.select_to_end_of_line(
6240 // &SelectToEndOfLine {
6241 // stop_at_soft_wraps: false,
6242 // },
6243 // cx,
6244 // );
6245 // this.cut(&Cut, cx);
6246 // });
6247 // }
6248
6249 // pub fn move_to_start_of_paragraph(
6250 // &mut self,
6251 // _: &MoveToStartOfParagraph,
6252 // cx: &mut ViewContext<Self>,
6253 // ) {
6254 // if matches!(self.mode, EditorMode::SingleLine) {
6255 // cx.propagate();
6256 // return;
6257 // }
6258
6259 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6260 // s.move_with(|map, selection| {
6261 // selection.collapse_to(
6262 // movement::start_of_paragraph(map, selection.head(), 1),
6263 // SelectionGoal::None,
6264 // )
6265 // });
6266 // })
6267 // }
6268
6269 // pub fn move_to_end_of_paragraph(
6270 // &mut self,
6271 // _: &MoveToEndOfParagraph,
6272 // cx: &mut ViewContext<Self>,
6273 // ) {
6274 // if matches!(self.mode, EditorMode::SingleLine) {
6275 // cx.propagate();
6276 // return;
6277 // }
6278
6279 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6280 // s.move_with(|map, selection| {
6281 // selection.collapse_to(
6282 // movement::end_of_paragraph(map, selection.head(), 1),
6283 // SelectionGoal::None,
6284 // )
6285 // });
6286 // })
6287 // }
6288
6289 // pub fn select_to_start_of_paragraph(
6290 // &mut self,
6291 // _: &SelectToStartOfParagraph,
6292 // cx: &mut ViewContext<Self>,
6293 // ) {
6294 // if matches!(self.mode, EditorMode::SingleLine) {
6295 // cx.propagate();
6296 // return;
6297 // }
6298
6299 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6300 // s.move_heads_with(|map, head, _| {
6301 // (
6302 // movement::start_of_paragraph(map, head, 1),
6303 // SelectionGoal::None,
6304 // )
6305 // });
6306 // })
6307 // }
6308
6309 // pub fn select_to_end_of_paragraph(
6310 // &mut self,
6311 // _: &SelectToEndOfParagraph,
6312 // cx: &mut ViewContext<Self>,
6313 // ) {
6314 // if matches!(self.mode, EditorMode::SingleLine) {
6315 // cx.propagate();
6316 // return;
6317 // }
6318
6319 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6320 // s.move_heads_with(|map, head, _| {
6321 // (
6322 // movement::end_of_paragraph(map, head, 1),
6323 // SelectionGoal::None,
6324 // )
6325 // });
6326 // })
6327 // }
6328
6329 // pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
6330 // if matches!(self.mode, EditorMode::SingleLine) {
6331 // cx.propagate();
6332 // return;
6333 // }
6334
6335 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6336 // s.select_ranges(vec![0..0]);
6337 // });
6338 // }
6339
6340 // pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
6341 // let mut selection = self.selections.last::<Point>(cx);
6342 // selection.set_head(Point::zero(), SelectionGoal::None);
6343
6344 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6345 // s.select(vec![selection]);
6346 // });
6347 // }
6348
6349 // pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
6350 // if matches!(self.mode, EditorMode::SingleLine) {
6351 // cx.propagate();
6352 // return;
6353 // }
6354
6355 // let cursor = self.buffer.read(cx).read(cx).len();
6356 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6357 // s.select_ranges(vec![cursor..cursor])
6358 // });
6359 // }
6360
6361 // pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
6362 // self.nav_history = nav_history;
6363 // }
6364
6365 // pub fn nav_history(&self) -> Option<&ItemNavHistory> {
6366 // self.nav_history.as_ref()
6367 // }
6368
6369 fn push_to_nav_history(
6370 &mut self,
6371 cursor_anchor: Anchor,
6372 new_position: Option<Point>,
6373 cx: &mut ViewContext<Self>,
6374 ) {
6375 if let Some(nav_history) = self.nav_history.as_mut() {
6376 let buffer = self.buffer.read(cx).read(cx);
6377 let cursor_position = cursor_anchor.to_point(&buffer);
6378 let scroll_state = self.scroll_manager.anchor();
6379 let scroll_top_row = scroll_state.top_row(&buffer);
6380 drop(buffer);
6381
6382 if let Some(new_position) = new_position {
6383 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6384 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6385 return;
6386 }
6387 }
6388
6389 nav_history.push(
6390 Some(NavigationData {
6391 cursor_anchor,
6392 cursor_position,
6393 scroll_anchor: scroll_state,
6394 scroll_top_row,
6395 }),
6396 cx,
6397 );
6398 }
6399 }
6400
6401 // pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6402 // let buffer = self.buffer.read(cx).snapshot(cx);
6403 // let mut selection = self.selections.first::<usize>(cx);
6404 // selection.set_head(buffer.len(), SelectionGoal::None);
6405 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6406 // s.select(vec![selection]);
6407 // });
6408 // }
6409
6410 // pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6411 // let end = self.buffer.read(cx).read(cx).len();
6412 // self.change_selections(None, cx, |s| {
6413 // s.select_ranges(vec![0..end]);
6414 // });
6415 // }
6416
6417 // pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6418 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6419 // let mut selections = self.selections.all::<Point>(cx);
6420 // let max_point = display_map.buffer_snapshot.max_point();
6421 // for selection in &mut selections {
6422 // let rows = selection.spanned_rows(true, &display_map);
6423 // selection.start = Point::new(rows.start, 0);
6424 // selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6425 // selection.reversed = false;
6426 // }
6427 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6428 // s.select(selections);
6429 // });
6430 // }
6431
6432 // pub fn split_selection_into_lines(
6433 // &mut self,
6434 // _: &SplitSelectionIntoLines,
6435 // cx: &mut ViewContext<Self>,
6436 // ) {
6437 // let mut to_unfold = Vec::new();
6438 // let mut new_selection_ranges = Vec::new();
6439 // {
6440 // let selections = self.selections.all::<Point>(cx);
6441 // let buffer = self.buffer.read(cx).read(cx);
6442 // for selection in selections {
6443 // for row in selection.start.row..selection.end.row {
6444 // let cursor = Point::new(row, buffer.line_len(row));
6445 // new_selection_ranges.push(cursor..cursor);
6446 // }
6447 // new_selection_ranges.push(selection.end..selection.end);
6448 // to_unfold.push(selection.start..selection.end);
6449 // }
6450 // }
6451 // self.unfold_ranges(to_unfold, true, true, cx);
6452 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6453 // s.select_ranges(new_selection_ranges);
6454 // });
6455 // }
6456
6457 // pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6458 // self.add_selection(true, cx);
6459 // }
6460
6461 // pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6462 // self.add_selection(false, cx);
6463 // }
6464
6465 // fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6466 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6467 // let mut selections = self.selections.all::<Point>(cx);
6468 // let text_layout_details = self.text_layout_details(cx);
6469 // let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6470 // let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6471 // let range = oldest_selection.display_range(&display_map).sorted();
6472
6473 // let start_x = display_map.x_for_point(range.start, &text_layout_details);
6474 // let end_x = display_map.x_for_point(range.end, &text_layout_details);
6475 // let positions = start_x.min(end_x)..start_x.max(end_x);
6476
6477 // selections.clear();
6478 // let mut stack = Vec::new();
6479 // for row in range.start.row()..=range.end.row() {
6480 // if let Some(selection) = self.selections.build_columnar_selection(
6481 // &display_map,
6482 // row,
6483 // &positions,
6484 // oldest_selection.reversed,
6485 // &text_layout_details,
6486 // ) {
6487 // stack.push(selection.id);
6488 // selections.push(selection);
6489 // }
6490 // }
6491
6492 // if above {
6493 // stack.reverse();
6494 // }
6495
6496 // AddSelectionsState { above, stack }
6497 // });
6498
6499 // let last_added_selection = *state.stack.last().unwrap();
6500 // let mut new_selections = Vec::new();
6501 // if above == state.above {
6502 // let end_row = if above {
6503 // 0
6504 // } else {
6505 // display_map.max_point().row()
6506 // };
6507
6508 // 'outer: for selection in selections {
6509 // if selection.id == last_added_selection {
6510 // let range = selection.display_range(&display_map).sorted();
6511 // debug_assert_eq!(range.start.row(), range.end.row());
6512 // let mut row = range.start.row();
6513 // let positions = if let SelectionGoal::HorizontalRange { start, end } =
6514 // selection.goal
6515 // {
6516 // start..end
6517 // } else {
6518 // let start_x = display_map.x_for_point(range.start, &text_layout_details);
6519 // let end_x = display_map.x_for_point(range.end, &text_layout_details);
6520
6521 // start_x.min(end_x)..start_x.max(end_x)
6522 // };
6523
6524 // while row != end_row {
6525 // if above {
6526 // row -= 1;
6527 // } else {
6528 // row += 1;
6529 // }
6530
6531 // if let Some(new_selection) = self.selections.build_columnar_selection(
6532 // &display_map,
6533 // row,
6534 // &positions,
6535 // selection.reversed,
6536 // &text_layout_details,
6537 // ) {
6538 // state.stack.push(new_selection.id);
6539 // if above {
6540 // new_selections.push(new_selection);
6541 // new_selections.push(selection);
6542 // } else {
6543 // new_selections.push(selection);
6544 // new_selections.push(new_selection);
6545 // }
6546
6547 // continue 'outer;
6548 // }
6549 // }
6550 // }
6551
6552 // new_selections.push(selection);
6553 // }
6554 // } else {
6555 // new_selections = selections;
6556 // new_selections.retain(|s| s.id != last_added_selection);
6557 // state.stack.pop();
6558 // }
6559
6560 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6561 // s.select(new_selections);
6562 // });
6563 // if state.stack.len() > 1 {
6564 // self.add_selections_state = Some(state);
6565 // }
6566 // }
6567
6568 // pub fn select_next_match_internal(
6569 // &mut self,
6570 // display_map: &DisplaySnapshot,
6571 // replace_newest: bool,
6572 // autoscroll: Option<Autoscroll>,
6573 // cx: &mut ViewContext<Self>,
6574 // ) -> Result<()> {
6575 // fn select_next_match_ranges(
6576 // this: &mut Editor,
6577 // range: Range<usize>,
6578 // replace_newest: bool,
6579 // auto_scroll: Option<Autoscroll>,
6580 // cx: &mut ViewContext<Editor>,
6581 // ) {
6582 // this.unfold_ranges([range.clone()], false, true, cx);
6583 // this.change_selections(auto_scroll, cx, |s| {
6584 // if replace_newest {
6585 // s.delete(s.newest_anchor().id);
6586 // }
6587 // s.insert_range(range.clone());
6588 // });
6589 // }
6590
6591 // let buffer = &display_map.buffer_snapshot;
6592 // let mut selections = self.selections.all::<usize>(cx);
6593 // if let Some(mut select_next_state) = self.select_next_state.take() {
6594 // let query = &select_next_state.query;
6595 // if !select_next_state.done {
6596 // let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6597 // let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6598 // let mut next_selected_range = None;
6599
6600 // let bytes_after_last_selection =
6601 // buffer.bytes_in_range(last_selection.end..buffer.len());
6602 // let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6603 // let query_matches = query
6604 // .stream_find_iter(bytes_after_last_selection)
6605 // .map(|result| (last_selection.end, result))
6606 // .chain(
6607 // query
6608 // .stream_find_iter(bytes_before_first_selection)
6609 // .map(|result| (0, result)),
6610 // );
6611
6612 // for (start_offset, query_match) in query_matches {
6613 // let query_match = query_match.unwrap(); // can only fail due to I/O
6614 // let offset_range =
6615 // start_offset + query_match.start()..start_offset + query_match.end();
6616 // let display_range = offset_range.start.to_display_point(&display_map)
6617 // ..offset_range.end.to_display_point(&display_map);
6618
6619 // if !select_next_state.wordwise
6620 // || (!movement::is_inside_word(&display_map, display_range.start)
6621 // && !movement::is_inside_word(&display_map, display_range.end))
6622 // {
6623 // if selections
6624 // .iter()
6625 // .find(|selection| selection.range().overlaps(&offset_range))
6626 // .is_none()
6627 // {
6628 // next_selected_range = Some(offset_range);
6629 // break;
6630 // }
6631 // }
6632 // }
6633
6634 // if let Some(next_selected_range) = next_selected_range {
6635 // select_next_match_ranges(
6636 // self,
6637 // next_selected_range,
6638 // replace_newest,
6639 // autoscroll,
6640 // cx,
6641 // );
6642 // } else {
6643 // select_next_state.done = true;
6644 // }
6645 // }
6646
6647 // self.select_next_state = Some(select_next_state);
6648 // } else if selections.len() == 1 {
6649 // let selection = selections.last_mut().unwrap();
6650 // if selection.start == selection.end {
6651 // let word_range = movement::surrounding_word(
6652 // &display_map,
6653 // selection.start.to_display_point(&display_map),
6654 // );
6655 // selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6656 // selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6657 // selection.goal = SelectionGoal::None;
6658 // selection.reversed = false;
6659
6660 // let query = buffer
6661 // .text_for_range(selection.start..selection.end)
6662 // .collect::<String>();
6663
6664 // let is_empty = query.is_empty();
6665 // let select_state = SelectNextState {
6666 // query: AhoCorasick::new(&[query])?,
6667 // wordwise: true,
6668 // done: is_empty,
6669 // };
6670 // select_next_match_ranges(
6671 // self,
6672 // selection.start..selection.end,
6673 // replace_newest,
6674 // autoscroll,
6675 // cx,
6676 // );
6677 // self.select_next_state = Some(select_state);
6678 // } else {
6679 // let query = buffer
6680 // .text_for_range(selection.start..selection.end)
6681 // .collect::<String>();
6682 // self.select_next_state = Some(SelectNextState {
6683 // query: AhoCorasick::new(&[query])?,
6684 // wordwise: false,
6685 // done: false,
6686 // });
6687 // self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6688 // }
6689 // }
6690 // Ok(())
6691 // }
6692
6693 // pub fn select_all_matches(
6694 // &mut self,
6695 // action: &SelectAllMatches,
6696 // cx: &mut ViewContext<Self>,
6697 // ) -> Result<()> {
6698 // self.push_to_selection_history();
6699 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6700
6701 // loop {
6702 // self.select_next_match_internal(&display_map, action.replace_newest, None, cx)?;
6703
6704 // if self
6705 // .select_next_state
6706 // .as_ref()
6707 // .map(|selection_state| selection_state.done)
6708 // .unwrap_or(true)
6709 // {
6710 // break;
6711 // }
6712 // }
6713
6714 // Ok(())
6715 // }
6716
6717 // pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6718 // self.push_to_selection_history();
6719 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6720 // self.select_next_match_internal(
6721 // &display_map,
6722 // action.replace_newest,
6723 // Some(Autoscroll::newest()),
6724 // cx,
6725 // )?;
6726 // Ok(())
6727 // }
6728
6729 // pub fn select_previous(
6730 // &mut self,
6731 // action: &SelectPrevious,
6732 // cx: &mut ViewContext<Self>,
6733 // ) -> Result<()> {
6734 // self.push_to_selection_history();
6735 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6736 // let buffer = &display_map.buffer_snapshot;
6737 // let mut selections = self.selections.all::<usize>(cx);
6738 // if let Some(mut select_prev_state) = self.select_prev_state.take() {
6739 // let query = &select_prev_state.query;
6740 // if !select_prev_state.done {
6741 // let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6742 // let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6743 // let mut next_selected_range = None;
6744 // // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6745 // let bytes_before_last_selection =
6746 // buffer.reversed_bytes_in_range(0..last_selection.start);
6747 // let bytes_after_first_selection =
6748 // buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6749 // let query_matches = query
6750 // .stream_find_iter(bytes_before_last_selection)
6751 // .map(|result| (last_selection.start, result))
6752 // .chain(
6753 // query
6754 // .stream_find_iter(bytes_after_first_selection)
6755 // .map(|result| (buffer.len(), result)),
6756 // );
6757 // for (end_offset, query_match) in query_matches {
6758 // let query_match = query_match.unwrap(); // can only fail due to I/O
6759 // let offset_range =
6760 // end_offset - query_match.end()..end_offset - query_match.start();
6761 // let display_range = offset_range.start.to_display_point(&display_map)
6762 // ..offset_range.end.to_display_point(&display_map);
6763
6764 // if !select_prev_state.wordwise
6765 // || (!movement::is_inside_word(&display_map, display_range.start)
6766 // && !movement::is_inside_word(&display_map, display_range.end))
6767 // {
6768 // next_selected_range = Some(offset_range);
6769 // break;
6770 // }
6771 // }
6772
6773 // if let Some(next_selected_range) = next_selected_range {
6774 // self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6775 // self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6776 // if action.replace_newest {
6777 // s.delete(s.newest_anchor().id);
6778 // }
6779 // s.insert_range(next_selected_range);
6780 // });
6781 // } else {
6782 // select_prev_state.done = true;
6783 // }
6784 // }
6785
6786 // self.select_prev_state = Some(select_prev_state);
6787 // } else if selections.len() == 1 {
6788 // let selection = selections.last_mut().unwrap();
6789 // if selection.start == selection.end {
6790 // let word_range = movement::surrounding_word(
6791 // &display_map,
6792 // selection.start.to_display_point(&display_map),
6793 // );
6794 // selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6795 // selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6796 // selection.goal = SelectionGoal::None;
6797 // selection.reversed = false;
6798
6799 // let query = buffer
6800 // .text_for_range(selection.start..selection.end)
6801 // .collect::<String>();
6802 // let query = query.chars().rev().collect::<String>();
6803 // let select_state = SelectNextState {
6804 // query: AhoCorasick::new(&[query])?,
6805 // wordwise: true,
6806 // done: false,
6807 // };
6808 // self.unfold_ranges([selection.start..selection.end], false, true, cx);
6809 // self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6810 // s.select(selections);
6811 // });
6812 // self.select_prev_state = Some(select_state);
6813 // } else {
6814 // let query = buffer
6815 // .text_for_range(selection.start..selection.end)
6816 // .collect::<String>();
6817 // let query = query.chars().rev().collect::<String>();
6818 // self.select_prev_state = Some(SelectNextState {
6819 // query: AhoCorasick::new(&[query])?,
6820 // wordwise: false,
6821 // done: false,
6822 // });
6823 // self.select_previous(action, cx)?;
6824 // }
6825 // }
6826 // Ok(())
6827 // }
6828
6829 // pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
6830 // let text_layout_details = &self.text_layout_details(cx);
6831 // self.transact(cx, |this, cx| {
6832 // let mut selections = this.selections.all::<Point>(cx);
6833 // let mut edits = Vec::new();
6834 // let mut selection_edit_ranges = Vec::new();
6835 // let mut last_toggled_row = None;
6836 // let snapshot = this.buffer.read(cx).read(cx);
6837 // let empty_str: Arc<str> = "".into();
6838 // let mut suffixes_inserted = Vec::new();
6839
6840 // fn comment_prefix_range(
6841 // snapshot: &MultiBufferSnapshot,
6842 // row: u32,
6843 // comment_prefix: &str,
6844 // comment_prefix_whitespace: &str,
6845 // ) -> Range<Point> {
6846 // let start = Point::new(row, snapshot.indent_size_for_line(row).len);
6847
6848 // let mut line_bytes = snapshot
6849 // .bytes_in_range(start..snapshot.max_point())
6850 // .flatten()
6851 // .copied();
6852
6853 // // If this line currently begins with the line comment prefix, then record
6854 // // the range containing the prefix.
6855 // if line_bytes
6856 // .by_ref()
6857 // .take(comment_prefix.len())
6858 // .eq(comment_prefix.bytes())
6859 // {
6860 // // Include any whitespace that matches the comment prefix.
6861 // let matching_whitespace_len = line_bytes
6862 // .zip(comment_prefix_whitespace.bytes())
6863 // .take_while(|(a, b)| a == b)
6864 // .count() as u32;
6865 // let end = Point::new(
6866 // start.row,
6867 // start.column + comment_prefix.len() as u32 + matching_whitespace_len,
6868 // );
6869 // start..end
6870 // } else {
6871 // start..start
6872 // }
6873 // }
6874
6875 // fn comment_suffix_range(
6876 // snapshot: &MultiBufferSnapshot,
6877 // row: u32,
6878 // comment_suffix: &str,
6879 // comment_suffix_has_leading_space: bool,
6880 // ) -> Range<Point> {
6881 // let end = Point::new(row, snapshot.line_len(row));
6882 // let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
6883
6884 // let mut line_end_bytes = snapshot
6885 // .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
6886 // .flatten()
6887 // .copied();
6888
6889 // let leading_space_len = if suffix_start_column > 0
6890 // && line_end_bytes.next() == Some(b' ')
6891 // && comment_suffix_has_leading_space
6892 // {
6893 // 1
6894 // } else {
6895 // 0
6896 // };
6897
6898 // // If this line currently begins with the line comment prefix, then record
6899 // // the range containing the prefix.
6900 // if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
6901 // let start = Point::new(end.row, suffix_start_column - leading_space_len);
6902 // start..end
6903 // } else {
6904 // end..end
6905 // }
6906 // }
6907
6908 // // TODO: Handle selections that cross excerpts
6909 // for selection in &mut selections {
6910 // let start_column = snapshot.indent_size_for_line(selection.start.row).len;
6911 // let language = if let Some(language) =
6912 // snapshot.language_scope_at(Point::new(selection.start.row, start_column))
6913 // {
6914 // language
6915 // } else {
6916 // continue;
6917 // };
6918
6919 // selection_edit_ranges.clear();
6920
6921 // // If multiple selections contain a given row, avoid processing that
6922 // // row more than once.
6923 // let mut start_row = selection.start.row;
6924 // if last_toggled_row == Some(start_row) {
6925 // start_row += 1;
6926 // }
6927 // let end_row =
6928 // if selection.end.row > selection.start.row && selection.end.column == 0 {
6929 // selection.end.row - 1
6930 // } else {
6931 // selection.end.row
6932 // };
6933 // last_toggled_row = Some(end_row);
6934
6935 // if start_row > end_row {
6936 // continue;
6937 // }
6938
6939 // // If the language has line comments, toggle those.
6940 // if let Some(full_comment_prefix) = language.line_comment_prefix() {
6941 // // Split the comment prefix's trailing whitespace into a separate string,
6942 // // as that portion won't be used for detecting if a line is a comment.
6943 // let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6944 // let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6945 // let mut all_selection_lines_are_comments = true;
6946
6947 // for row in start_row..=end_row {
6948 // if snapshot.is_line_blank(row) && start_row < end_row {
6949 // continue;
6950 // }
6951
6952 // let prefix_range = comment_prefix_range(
6953 // snapshot.deref(),
6954 // row,
6955 // comment_prefix,
6956 // comment_prefix_whitespace,
6957 // );
6958 // if prefix_range.is_empty() {
6959 // all_selection_lines_are_comments = false;
6960 // }
6961 // selection_edit_ranges.push(prefix_range);
6962 // }
6963
6964 // if all_selection_lines_are_comments {
6965 // edits.extend(
6966 // selection_edit_ranges
6967 // .iter()
6968 // .cloned()
6969 // .map(|range| (range, empty_str.clone())),
6970 // );
6971 // } else {
6972 // let min_column = selection_edit_ranges
6973 // .iter()
6974 // .map(|r| r.start.column)
6975 // .min()
6976 // .unwrap_or(0);
6977 // edits.extend(selection_edit_ranges.iter().map(|range| {
6978 // let position = Point::new(range.start.row, min_column);
6979 // (position..position, full_comment_prefix.clone())
6980 // }));
6981 // }
6982 // } else if let Some((full_comment_prefix, comment_suffix)) =
6983 // language.block_comment_delimiters()
6984 // {
6985 // let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6986 // let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6987 // let prefix_range = comment_prefix_range(
6988 // snapshot.deref(),
6989 // start_row,
6990 // comment_prefix,
6991 // comment_prefix_whitespace,
6992 // );
6993 // let suffix_range = comment_suffix_range(
6994 // snapshot.deref(),
6995 // end_row,
6996 // comment_suffix.trim_start_matches(' '),
6997 // comment_suffix.starts_with(' '),
6998 // );
6999
7000 // if prefix_range.is_empty() || suffix_range.is_empty() {
7001 // edits.push((
7002 // prefix_range.start..prefix_range.start,
7003 // full_comment_prefix.clone(),
7004 // ));
7005 // edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
7006 // suffixes_inserted.push((end_row, comment_suffix.len()));
7007 // } else {
7008 // edits.push((prefix_range, empty_str.clone()));
7009 // edits.push((suffix_range, empty_str.clone()));
7010 // }
7011 // } else {
7012 // continue;
7013 // }
7014 // }
7015
7016 // drop(snapshot);
7017 // this.buffer.update(cx, |buffer, cx| {
7018 // buffer.edit(edits, None, cx);
7019 // });
7020
7021 // // Adjust selections so that they end before any comment suffixes that
7022 // // were inserted.
7023 // let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
7024 // let mut selections = this.selections.all::<Point>(cx);
7025 // let snapshot = this.buffer.read(cx).read(cx);
7026 // for selection in &mut selections {
7027 // while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
7028 // match row.cmp(&selection.end.row) {
7029 // Ordering::Less => {
7030 // suffixes_inserted.next();
7031 // continue;
7032 // }
7033 // Ordering::Greater => break,
7034 // Ordering::Equal => {
7035 // if selection.end.column == snapshot.line_len(row) {
7036 // if selection.is_empty() {
7037 // selection.start.column -= suffix_len as u32;
7038 // }
7039 // selection.end.column -= suffix_len as u32;
7040 // }
7041 // break;
7042 // }
7043 // }
7044 // }
7045 // }
7046
7047 // drop(snapshot);
7048 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7049
7050 // let selections = this.selections.all::<Point>(cx);
7051 // let selections_on_single_row = selections.windows(2).all(|selections| {
7052 // selections[0].start.row == selections[1].start.row
7053 // && selections[0].end.row == selections[1].end.row
7054 // && selections[0].start.row == selections[0].end.row
7055 // });
7056 // let selections_selecting = selections
7057 // .iter()
7058 // .any(|selection| selection.start != selection.end);
7059 // let advance_downwards = action.advance_downwards
7060 // && selections_on_single_row
7061 // && !selections_selecting
7062 // && this.mode != EditorMode::SingleLine;
7063
7064 // if advance_downwards {
7065 // let snapshot = this.buffer.read(cx).snapshot(cx);
7066
7067 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 // s.move_cursors_with(|display_snapshot, display_point, _| {
7069 // let mut point = display_point.to_point(display_snapshot);
7070 // point.row += 1;
7071 // point = snapshot.clip_point(point, Bias::Left);
7072 // let display_point = point.to_display_point(display_snapshot);
7073 // let goal = SelectionGoal::HorizontalPosition(
7074 // display_snapshot.x_for_point(display_point, &text_layout_details),
7075 // );
7076 // (display_point, goal)
7077 // })
7078 // });
7079 // }
7080 // });
7081 // }
7082
7083 // pub fn select_larger_syntax_node(
7084 // &mut self,
7085 // _: &SelectLargerSyntaxNode,
7086 // cx: &mut ViewContext<Self>,
7087 // ) {
7088 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7089 // let buffer = self.buffer.read(cx).snapshot(cx);
7090 // let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7091
7092 // let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7093 // let mut selected_larger_node = false;
7094 // let new_selections = old_selections
7095 // .iter()
7096 // .map(|selection| {
7097 // let old_range = selection.start..selection.end;
7098 // let mut new_range = old_range.clone();
7099 // while let Some(containing_range) =
7100 // buffer.range_for_syntax_ancestor(new_range.clone())
7101 // {
7102 // new_range = containing_range;
7103 // if !display_map.intersects_fold(new_range.start)
7104 // && !display_map.intersects_fold(new_range.end)
7105 // {
7106 // break;
7107 // }
7108 // }
7109
7110 // selected_larger_node |= new_range != old_range;
7111 // Selection {
7112 // id: selection.id,
7113 // start: new_range.start,
7114 // end: new_range.end,
7115 // goal: SelectionGoal::None,
7116 // reversed: selection.reversed,
7117 // }
7118 // })
7119 // .collect::<Vec<_>>();
7120
7121 // if selected_larger_node {
7122 // stack.push(old_selections);
7123 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7124 // s.select(new_selections);
7125 // });
7126 // }
7127 // self.select_larger_syntax_node_stack = stack;
7128 // }
7129
7130 // pub fn select_smaller_syntax_node(
7131 // &mut self,
7132 // _: &SelectSmallerSyntaxNode,
7133 // cx: &mut ViewContext<Self>,
7134 // ) {
7135 // let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7136 // if let Some(selections) = stack.pop() {
7137 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7138 // s.select(selections.to_vec());
7139 // });
7140 // }
7141 // self.select_larger_syntax_node_stack = stack;
7142 // }
7143
7144 // pub fn move_to_enclosing_bracket(
7145 // &mut self,
7146 // _: &MoveToEnclosingBracket,
7147 // cx: &mut ViewContext<Self>,
7148 // ) {
7149 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7150 // s.move_offsets_with(|snapshot, selection| {
7151 // let Some(enclosing_bracket_ranges) =
7152 // snapshot.enclosing_bracket_ranges(selection.start..selection.end)
7153 // else {
7154 // return;
7155 // };
7156
7157 // let mut best_length = usize::MAX;
7158 // let mut best_inside = false;
7159 // let mut best_in_bracket_range = false;
7160 // let mut best_destination = None;
7161 // for (open, close) in enclosing_bracket_ranges {
7162 // let close = close.to_inclusive();
7163 // let length = close.end() - open.start;
7164 // let inside = selection.start >= open.end && selection.end <= *close.start();
7165 // let in_bracket_range = open.to_inclusive().contains(&selection.head())
7166 // || close.contains(&selection.head());
7167
7168 // // If best is next to a bracket and current isn't, skip
7169 // if !in_bracket_range && best_in_bracket_range {
7170 // continue;
7171 // }
7172
7173 // // Prefer smaller lengths unless best is inside and current isn't
7174 // if length > best_length && (best_inside || !inside) {
7175 // continue;
7176 // }
7177
7178 // best_length = length;
7179 // best_inside = inside;
7180 // best_in_bracket_range = in_bracket_range;
7181 // best_destination = Some(
7182 // if close.contains(&selection.start) && close.contains(&selection.end) {
7183 // if inside {
7184 // open.end
7185 // } else {
7186 // open.start
7187 // }
7188 // } else {
7189 // if inside {
7190 // *close.start()
7191 // } else {
7192 // *close.end()
7193 // }
7194 // },
7195 // );
7196 // }
7197
7198 // if let Some(destination) = best_destination {
7199 // selection.collapse_to(destination, SelectionGoal::None);
7200 // }
7201 // })
7202 // });
7203 // }
7204
7205 // pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
7206 // self.end_selection(cx);
7207 // self.selection_history.mode = SelectionHistoryMode::Undoing;
7208 // if let Some(entry) = self.selection_history.undo_stack.pop_back() {
7209 // self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7210 // self.select_next_state = entry.select_next_state;
7211 // self.select_prev_state = entry.select_prev_state;
7212 // self.add_selections_state = entry.add_selections_state;
7213 // self.request_autoscroll(Autoscroll::newest(), cx);
7214 // }
7215 // self.selection_history.mode = SelectionHistoryMode::Normal;
7216 // }
7217
7218 // pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
7219 // self.end_selection(cx);
7220 // self.selection_history.mode = SelectionHistoryMode::Redoing;
7221 // if let Some(entry) = self.selection_history.redo_stack.pop_back() {
7222 // self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7223 // self.select_next_state = entry.select_next_state;
7224 // self.select_prev_state = entry.select_prev_state;
7225 // self.add_selections_state = entry.add_selections_state;
7226 // self.request_autoscroll(Autoscroll::newest(), cx);
7227 // }
7228 // self.selection_history.mode = SelectionHistoryMode::Normal;
7229 // }
7230
7231 // fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
7232 // self.go_to_diagnostic_impl(Direction::Next, cx)
7233 // }
7234
7235 // fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
7236 // self.go_to_diagnostic_impl(Direction::Prev, cx)
7237 // }
7238
7239 // pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
7240 // let buffer = self.buffer.read(cx).snapshot(cx);
7241 // let selection = self.selections.newest::<usize>(cx);
7242
7243 // // If there is an active Diagnostic Popover. Jump to it's diagnostic instead.
7244 // if direction == Direction::Next {
7245 // if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
7246 // let (group_id, jump_to) = popover.activation_info();
7247 // if self.activate_diagnostics(group_id, cx) {
7248 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7249 // let mut new_selection = s.newest_anchor().clone();
7250 // new_selection.collapse_to(jump_to, SelectionGoal::None);
7251 // s.select_anchors(vec![new_selection.clone()]);
7252 // });
7253 // }
7254 // return;
7255 // }
7256 // }
7257
7258 // let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
7259 // active_diagnostics
7260 // .primary_range
7261 // .to_offset(&buffer)
7262 // .to_inclusive()
7263 // });
7264 // let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
7265 // if active_primary_range.contains(&selection.head()) {
7266 // *active_primary_range.end()
7267 // } else {
7268 // selection.head()
7269 // }
7270 // } else {
7271 // selection.head()
7272 // };
7273
7274 // loop {
7275 // let mut diagnostics = if direction == Direction::Prev {
7276 // buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
7277 // } else {
7278 // buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
7279 // };
7280 // let group = diagnostics.find_map(|entry| {
7281 // if entry.diagnostic.is_primary
7282 // && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
7283 // && !entry.range.is_empty()
7284 // && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7285 // && !entry.range.contains(&search_start)
7286 // {
7287 // Some((entry.range, entry.diagnostic.group_id))
7288 // } else {
7289 // None
7290 // }
7291 // });
7292
7293 // if let Some((primary_range, group_id)) = group {
7294 // if self.activate_diagnostics(group_id, cx) {
7295 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7296 // s.select(vec![Selection {
7297 // id: selection.id,
7298 // start: primary_range.start,
7299 // end: primary_range.start,
7300 // reversed: false,
7301 // goal: SelectionGoal::None,
7302 // }]);
7303 // });
7304 // }
7305 // break;
7306 // } else {
7307 // // Cycle around to the start of the buffer, potentially moving back to the start of
7308 // // the currently active diagnostic.
7309 // active_primary_range.take();
7310 // if direction == Direction::Prev {
7311 // if search_start == buffer.len() {
7312 // break;
7313 // } else {
7314 // search_start = buffer.len();
7315 // }
7316 // } else if search_start == 0 {
7317 // break;
7318 // } else {
7319 // search_start = 0;
7320 // }
7321 // }
7322 // }
7323 // }
7324
7325 // fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7326 // let snapshot = self
7327 // .display_map
7328 // .update(cx, |display_map, cx| display_map.snapshot(cx));
7329 // let selection = self.selections.newest::<Point>(cx);
7330
7331 // if !self.seek_in_direction(
7332 // &snapshot,
7333 // selection.head(),
7334 // false,
7335 // snapshot
7336 // .buffer_snapshot
7337 // .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7338 // cx,
7339 // ) {
7340 // let wrapped_point = Point::zero();
7341 // self.seek_in_direction(
7342 // &snapshot,
7343 // wrapped_point,
7344 // true,
7345 // snapshot
7346 // .buffer_snapshot
7347 // .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7348 // cx,
7349 // );
7350 // }
7351 // }
7352
7353 // fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7354 // let snapshot = self
7355 // .display_map
7356 // .update(cx, |display_map, cx| display_map.snapshot(cx));
7357 // let selection = self.selections.newest::<Point>(cx);
7358
7359 // if !self.seek_in_direction(
7360 // &snapshot,
7361 // selection.head(),
7362 // false,
7363 // snapshot
7364 // .buffer_snapshot
7365 // .git_diff_hunks_in_range_rev(0..selection.head().row),
7366 // cx,
7367 // ) {
7368 // let wrapped_point = snapshot.buffer_snapshot.max_point();
7369 // self.seek_in_direction(
7370 // &snapshot,
7371 // wrapped_point,
7372 // true,
7373 // snapshot
7374 // .buffer_snapshot
7375 // .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7376 // cx,
7377 // );
7378 // }
7379 // }
7380
7381 // fn seek_in_direction(
7382 // &mut self,
7383 // snapshot: &DisplaySnapshot,
7384 // initial_point: Point,
7385 // is_wrapped: bool,
7386 // hunks: impl Iterator<Item = DiffHunk<u32>>,
7387 // cx: &mut ViewContext<Editor>,
7388 // ) -> bool {
7389 // let display_point = initial_point.to_display_point(snapshot);
7390 // let mut hunks = hunks
7391 // .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
7392 // .filter(|hunk| {
7393 // if is_wrapped {
7394 // true
7395 // } else {
7396 // !hunk.contains_display_row(display_point.row())
7397 // }
7398 // })
7399 // .dedup();
7400
7401 // if let Some(hunk) = hunks.next() {
7402 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7403 // let row = hunk.start_display_row();
7404 // let point = DisplayPoint::new(row, 0);
7405 // s.select_display_ranges([point..point]);
7406 // });
7407
7408 // true
7409 // } else {
7410 // false
7411 // }
7412 // }
7413
7414 pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
7415 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
7416 }
7417
7418 pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
7419 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
7420 }
7421
7422 pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
7423 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
7424 }
7425
7426 pub fn go_to_type_definition_split(
7427 &mut self,
7428 _: &GoToTypeDefinitionSplit,
7429 cx: &mut ViewContext<Self>,
7430 ) {
7431 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
7432 }
7433
7434 fn go_to_definition_of_kind(
7435 &mut self,
7436 kind: GotoDefinitionKind,
7437 split: bool,
7438 cx: &mut ViewContext<Self>,
7439 ) {
7440 let Some(workspace) = self.workspace() else {
7441 return;
7442 };
7443 let buffer = self.buffer.read(cx);
7444 let head = self.selections.newest::<usize>(cx).head();
7445 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7446 text_anchor
7447 } else {
7448 return;
7449 };
7450
7451 let project = workspace.read(cx).project().clone();
7452 let definitions = project.update(cx, |project, cx| match kind {
7453 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7454 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7455 });
7456
7457 cx.spawn(|editor, mut cx| async move {
7458 let definitions = definitions.await?;
7459 editor.update(&mut cx, |editor, cx| {
7460 editor.navigate_to_definitions(
7461 definitions
7462 .into_iter()
7463 .map(GoToDefinitionLink::Text)
7464 .collect(),
7465 split,
7466 cx,
7467 );
7468 })?;
7469 Ok::<(), anyhow::Error>(())
7470 })
7471 .detach_and_log_err(cx);
7472 }
7473
7474 pub fn navigate_to_definitions(
7475 &mut self,
7476 mut definitions: Vec<GoToDefinitionLink>,
7477 split: bool,
7478 cx: &mut ViewContext<Editor>,
7479 ) {
7480 let Some(workspace) = self.workspace() else {
7481 return;
7482 };
7483 let pane = workspace.read(cx).active_pane().clone();
7484 // If there is one definition, just open it directly
7485 if definitions.len() == 1 {
7486 let definition = definitions.pop().unwrap();
7487 let target_task = match definition {
7488 GoToDefinitionLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7489 GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7490 self.compute_target_location(lsp_location, server_id, cx)
7491 }
7492 };
7493 cx.spawn(|editor, mut cx| async move {
7494 let target = target_task.await.context("target resolution task")?;
7495 if let Some(target) = target {
7496 editor.update(&mut cx, |editor, cx| {
7497 let range = target.range.to_offset(target.buffer.read(cx));
7498 let range = editor.range_for_match(&range);
7499 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7500 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7501 s.select_ranges([range]);
7502 });
7503 } else {
7504 cx.window_context().defer(move |cx| {
7505 let target_editor: View<Self> =
7506 workspace.update(cx, |workspace, cx| {
7507 if split {
7508 workspace.split_project_item(target.buffer.clone(), cx)
7509 } else {
7510 workspace.open_project_item(target.buffer.clone(), cx)
7511 }
7512 });
7513 target_editor.update(cx, |target_editor, cx| {
7514 // When selecting a definition in a different buffer, disable the nav history
7515 // to avoid creating a history entry at the previous cursor location.
7516 pane.update(cx, |pane, _| pane.disable_history());
7517 target_editor.change_selections(
7518 Some(Autoscroll::fit()),
7519 cx,
7520 |s| {
7521 s.select_ranges([range]);
7522 },
7523 );
7524 pane.update(cx, |pane, _| pane.enable_history());
7525 });
7526 });
7527 }
7528 })
7529 } else {
7530 Ok(())
7531 }
7532 })
7533 .detach_and_log_err(cx);
7534 } else if !definitions.is_empty() {
7535 let replica_id = self.replica_id(cx);
7536 cx.spawn(|editor, mut cx| async move {
7537 let (title, location_tasks) = editor
7538 .update(&mut cx, |editor, cx| {
7539 let title = definitions
7540 .iter()
7541 .find_map(|definition| match definition {
7542 GoToDefinitionLink::Text(link) => {
7543 link.origin.as_ref().map(|origin| {
7544 let buffer = origin.buffer.read(cx);
7545 format!(
7546 "Definitions for {}",
7547 buffer
7548 .text_for_range(origin.range.clone())
7549 .collect::<String>()
7550 )
7551 })
7552 }
7553 GoToDefinitionLink::InlayHint(_, _) => None,
7554 })
7555 .unwrap_or("Definitions".to_string());
7556 let location_tasks = definitions
7557 .into_iter()
7558 .map(|definition| match definition {
7559 GoToDefinitionLink::Text(link) => {
7560 Task::Ready(Some(Ok(Some(link.target))))
7561 }
7562 GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7563 editor.compute_target_location(lsp_location, server_id, cx)
7564 }
7565 })
7566 .collect::<Vec<_>>();
7567 (title, location_tasks)
7568 })
7569 .context("location tasks preparation")?;
7570
7571 let locations = futures::future::join_all(location_tasks)
7572 .await
7573 .into_iter()
7574 .filter_map(|location| location.transpose())
7575 .collect::<Result<_>>()
7576 .context("location tasks")?;
7577 workspace.update(&mut cx, |workspace, cx| {
7578 Self::open_locations_in_multibuffer(
7579 workspace, locations, replica_id, title, split, cx,
7580 )
7581 });
7582
7583 anyhow::Ok(())
7584 })
7585 .detach_and_log_err(cx);
7586 }
7587 }
7588
7589 fn compute_target_location(
7590 &self,
7591 lsp_location: lsp::Location,
7592 server_id: LanguageServerId,
7593 cx: &mut ViewContext<Editor>,
7594 ) -> Task<anyhow::Result<Option<Location>>> {
7595 let Some(project) = self.project.clone() else {
7596 return Task::Ready(Some(Ok(None)));
7597 };
7598
7599 cx.spawn(move |editor, mut cx| async move {
7600 let location_task = editor.update(&mut cx, |editor, cx| {
7601 project.update(cx, |project, cx| {
7602 let language_server_name =
7603 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7604 project
7605 .language_server_for_buffer(buffer.read(cx), server_id, cx)
7606 .map(|(_, lsp_adapter)| {
7607 LanguageServerName(Arc::from(lsp_adapter.name()))
7608 })
7609 });
7610 language_server_name.map(|language_server_name| {
7611 project.open_local_buffer_via_lsp(
7612 lsp_location.uri.clone(),
7613 server_id,
7614 language_server_name,
7615 cx,
7616 )
7617 })
7618 })
7619 })?;
7620 let location = match location_task {
7621 Some(task) => Some({
7622 let target_buffer_handle = task.await.context("open local buffer")?;
7623 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
7624 let target_start = target_buffer
7625 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
7626 let target_end = target_buffer
7627 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
7628 target_buffer.anchor_after(target_start)
7629 ..target_buffer.anchor_before(target_end)
7630 })?;
7631 Location {
7632 buffer: target_buffer_handle,
7633 range,
7634 }
7635 }),
7636 None => None,
7637 };
7638 Ok(location)
7639 })
7640 }
7641
7642 // pub fn find_all_references(
7643 // workspace: &mut Workspace,
7644 // _: &FindAllReferences,
7645 // cx: &mut ViewContext<Workspace>,
7646 // ) -> Option<Task<Result<()>>> {
7647 // let active_item = workspace.active_item(cx)?;
7648 // let editor_handle = active_item.act_as::<Self>(cx)?;
7649
7650 // let editor = editor_handle.read(cx);
7651 // let buffer = editor.buffer.read(cx);
7652 // let head = editor.selections.newest::<usize>(cx).head();
7653 // let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
7654 // let replica_id = editor.replica_id(cx);
7655
7656 // let project = workspace.project().clone();
7657 // let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
7658 // Some(cx.spawn_labeled(
7659 // "Finding All References...",
7660 // |workspace, mut cx| async move {
7661 // let locations = references.await?;
7662 // if locations.is_empty() {
7663 // return Ok(());
7664 // }
7665
7666 // workspace.update(&mut cx, |workspace, cx| {
7667 // let title = locations
7668 // .first()
7669 // .as_ref()
7670 // .map(|location| {
7671 // let buffer = location.buffer.read(cx);
7672 // format!(
7673 // "References to `{}`",
7674 // buffer
7675 // .text_for_range(location.range.clone())
7676 // .collect::<String>()
7677 // )
7678 // })
7679 // .unwrap();
7680 // Self::open_locations_in_multibuffer(
7681 // workspace, locations, replica_id, title, false, cx,
7682 // );
7683 // })?;
7684
7685 // Ok(())
7686 // },
7687 // ))
7688 // }
7689
7690 /// Opens a multibuffer with the given project locations in it
7691 pub fn open_locations_in_multibuffer(
7692 workspace: &mut Workspace,
7693 mut locations: Vec<Location>,
7694 replica_id: ReplicaId,
7695 title: String,
7696 split: bool,
7697 cx: &mut ViewContext<Workspace>,
7698 ) {
7699 // If there are multiple definitions, open them in a multibuffer
7700 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
7701 let mut locations = locations.into_iter().peekable();
7702 let mut ranges_to_highlight = Vec::new();
7703
7704 let excerpt_buffer = cx.build_model(|cx| {
7705 let mut multibuffer = MultiBuffer::new(replica_id);
7706 while let Some(location) = locations.next() {
7707 let buffer = location.buffer.read(cx);
7708 let mut ranges_for_buffer = Vec::new();
7709 let range = location.range.to_offset(buffer);
7710 ranges_for_buffer.push(range.clone());
7711
7712 while let Some(next_location) = locations.peek() {
7713 if next_location.buffer == location.buffer {
7714 ranges_for_buffer.push(next_location.range.to_offset(buffer));
7715 locations.next();
7716 } else {
7717 break;
7718 }
7719 }
7720
7721 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
7722 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
7723 location.buffer.clone(),
7724 ranges_for_buffer,
7725 1,
7726 cx,
7727 ))
7728 }
7729
7730 multibuffer.with_title(title)
7731 });
7732
7733 let editor = cx.build_view(|cx| {
7734 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
7735 });
7736 editor.update(cx, |editor, cx| {
7737 editor.highlight_background::<Self>(
7738 ranges_to_highlight,
7739 |theme| todo!("theme.editor.highlighted_line_background"),
7740 cx,
7741 );
7742 });
7743 if split {
7744 workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
7745 } else {
7746 workspace.add_item(Box::new(editor), cx);
7747 }
7748 }
7749
7750 // pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7751 // use language::ToOffset as _;
7752
7753 // let project = self.project.clone()?;
7754 // let selection = self.selections.newest_anchor().clone();
7755 // let (cursor_buffer, cursor_buffer_position) = self
7756 // .buffer
7757 // .read(cx)
7758 // .text_anchor_for_position(selection.head(), cx)?;
7759 // let (tail_buffer, _) = self
7760 // .buffer
7761 // .read(cx)
7762 // .text_anchor_for_position(selection.tail(), cx)?;
7763 // if tail_buffer != cursor_buffer {
7764 // return None;
7765 // }
7766
7767 // let snapshot = cursor_buffer.read(cx).snapshot();
7768 // let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
7769 // let prepare_rename = project.update(cx, |project, cx| {
7770 // project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
7771 // });
7772
7773 // Some(cx.spawn(|this, mut cx| async move {
7774 // let rename_range = if let Some(range) = prepare_rename.await? {
7775 // Some(range)
7776 // } else {
7777 // this.update(&mut cx, |this, cx| {
7778 // let buffer = this.buffer.read(cx).snapshot(cx);
7779 // let mut buffer_highlights = this
7780 // .document_highlights_for_position(selection.head(), &buffer)
7781 // .filter(|highlight| {
7782 // highlight.start.excerpt_id == selection.head().excerpt_id
7783 // && highlight.end.excerpt_id == selection.head().excerpt_id
7784 // });
7785 // buffer_highlights
7786 // .next()
7787 // .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
7788 // })?
7789 // };
7790 // if let Some(rename_range) = rename_range {
7791 // let rename_buffer_range = rename_range.to_offset(&snapshot);
7792 // let cursor_offset_in_rename_range =
7793 // cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
7794
7795 // this.update(&mut cx, |this, cx| {
7796 // this.take_rename(false, cx);
7797 // let style = this.style(cx);
7798 // let buffer = this.buffer.read(cx).read(cx);
7799 // let cursor_offset = selection.head().to_offset(&buffer);
7800 // let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
7801 // let rename_end = rename_start + rename_buffer_range.len();
7802 // let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
7803 // let mut old_highlight_id = None;
7804 // let old_name: Arc<str> = buffer
7805 // .chunks(rename_start..rename_end, true)
7806 // .map(|chunk| {
7807 // if old_highlight_id.is_none() {
7808 // old_highlight_id = chunk.syntax_highlight_id;
7809 // }
7810 // chunk.text
7811 // })
7812 // .collect::<String>()
7813 // .into();
7814
7815 // drop(buffer);
7816
7817 // // Position the selection in the rename editor so that it matches the current selection.
7818 // this.show_local_selections = false;
7819 // let rename_editor = cx.add_view(|cx| {
7820 // let mut editor = Editor::single_line(None, cx);
7821 // if let Some(old_highlight_id) = old_highlight_id {
7822 // editor.override_text_style =
7823 // Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
7824 // }
7825 // editor.buffer.update(cx, |buffer, cx| {
7826 // buffer.edit([(0..0, old_name.clone())], None, cx)
7827 // });
7828 // editor.select_all(&SelectAll, cx);
7829 // editor
7830 // });
7831
7832 // let ranges = this
7833 // .clear_background_highlights::<DocumentHighlightWrite>(cx)
7834 // .into_iter()
7835 // .flat_map(|(_, ranges)| ranges.into_iter())
7836 // .chain(
7837 // this.clear_background_highlights::<DocumentHighlightRead>(cx)
7838 // .into_iter()
7839 // .flat_map(|(_, ranges)| ranges.into_iter()),
7840 // )
7841 // .collect();
7842
7843 // this.highlight_text::<Rename>(
7844 // ranges,
7845 // HighlightStyle {
7846 // fade_out: Some(style.rename_fade),
7847 // ..Default::default()
7848 // },
7849 // cx,
7850 // );
7851 // cx.focus(&rename_editor);
7852 // let block_id = this.insert_blocks(
7853 // [BlockProperties {
7854 // style: BlockStyle::Flex,
7855 // position: range.start.clone(),
7856 // height: 1,
7857 // render: Arc::new({
7858 // let editor = rename_editor.clone();
7859 // move |cx: &mut BlockContext| {
7860 // ChildView::new(&editor, cx)
7861 // .contained()
7862 // .with_padding_left(cx.anchor_x)
7863 // .into_any()
7864 // }
7865 // }),
7866 // disposition: BlockDisposition::Below,
7867 // }],
7868 // Some(Autoscroll::fit()),
7869 // cx,
7870 // )[0];
7871 // this.pending_rename = Some(RenameState {
7872 // range,
7873 // old_name,
7874 // editor: rename_editor,
7875 // block_id,
7876 // });
7877 // })?;
7878 // }
7879
7880 // Ok(())
7881 // }))
7882 // }
7883
7884 // pub fn confirm_rename(
7885 // workspace: &mut Workspace,
7886 // _: &ConfirmRename,
7887 // cx: &mut ViewContext<Workspace>,
7888 // ) -> Option<Task<Result<()>>> {
7889 // let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
7890
7891 // let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
7892 // let rename = editor.take_rename(false, cx)?;
7893 // let buffer = editor.buffer.read(cx);
7894 // let (start_buffer, start) =
7895 // buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
7896 // let (end_buffer, end) =
7897 // buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
7898 // if start_buffer == end_buffer {
7899 // let new_name = rename.editor.read(cx).text(cx);
7900 // Some((start_buffer, start..end, rename.old_name, new_name))
7901 // } else {
7902 // None
7903 // }
7904 // })?;
7905
7906 // let rename = workspace.project().clone().update(cx, |project, cx| {
7907 // project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
7908 // });
7909
7910 // let editor = editor.downgrade();
7911 // Some(cx.spawn(|workspace, mut cx| async move {
7912 // let project_transaction = rename.await?;
7913 // Self::open_project_transaction(
7914 // &editor,
7915 // workspace,
7916 // project_transaction,
7917 // format!("Rename: {} → {}", old_name, new_name),
7918 // cx.clone(),
7919 // )
7920 // .await?;
7921
7922 // editor.update(&mut cx, |editor, cx| {
7923 // editor.refresh_document_highlights(cx);
7924 // })?;
7925 // Ok(())
7926 // }))
7927 // }
7928
7929 fn take_rename(
7930 &mut self,
7931 moving_cursor: bool,
7932 cx: &mut ViewContext<Self>,
7933 ) -> Option<RenameState> {
7934 let rename = self.pending_rename.take()?;
7935 self.remove_blocks(
7936 [rename.block_id].into_iter().collect(),
7937 Some(Autoscroll::fit()),
7938 cx,
7939 );
7940 self.clear_highlights::<Rename>(cx);
7941 self.show_local_selections = true;
7942
7943 if moving_cursor {
7944 let rename_editor = rename.editor.read(cx);
7945 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
7946
7947 // Update the selection to match the position of the selection inside
7948 // the rename editor.
7949 let snapshot = self.buffer.read(cx).read(cx);
7950 let rename_range = rename.range.to_offset(&snapshot);
7951 let cursor_in_editor = snapshot
7952 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
7953 .min(rename_range.end);
7954 drop(snapshot);
7955
7956 self.change_selections(None, cx, |s| {
7957 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
7958 });
7959 } else {
7960 self.refresh_document_highlights(cx);
7961 }
7962
7963 Some(rename)
7964 }
7965
7966 #[cfg(any(test, feature = "test-support"))]
7967 pub fn pending_rename(&self) -> Option<&RenameState> {
7968 self.pending_rename.as_ref()
7969 }
7970
7971 // fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7972 // let project = match &self.project {
7973 // Some(project) => project.clone(),
7974 // None => return None,
7975 // };
7976
7977 // Some(self.perform_format(project, FormatTrigger::Manual, cx))
7978 // }
7979
7980 fn perform_format(
7981 &mut self,
7982 project: Model<Project>,
7983 trigger: FormatTrigger,
7984 cx: &mut ViewContext<Self>,
7985 ) -> Task<Result<()>> {
7986 let buffer = self.buffer().clone();
7987 let buffers = buffer.read(cx).all_buffers();
7988
7989 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
7990 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
7991
7992 cx.spawn(|_, mut cx| async move {
7993 let transaction = futures::select_biased! {
7994 _ = timeout => {
7995 log::warn!("timed out waiting for formatting");
7996 None
7997 }
7998 transaction = format.log_err().fuse() => transaction,
7999 };
8000
8001 buffer.update(&mut cx, |buffer, cx| {
8002 if let Some(transaction) = transaction {
8003 if !buffer.is_singleton() {
8004 buffer.push_transaction(&transaction.0, cx);
8005 }
8006 }
8007
8008 cx.notify();
8009 });
8010
8011 Ok(())
8012 })
8013 }
8014
8015 // fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
8016 // if let Some(project) = self.project.clone() {
8017 // self.buffer.update(cx, |multi_buffer, cx| {
8018 // project.update(cx, |project, cx| {
8019 // project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
8020 // });
8021 // })
8022 // }
8023 // }
8024
8025 // fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
8026 // cx.show_character_palette();
8027 // }
8028
8029 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
8030 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
8031 let buffer = self.buffer.read(cx).snapshot(cx);
8032 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
8033 let is_valid = buffer
8034 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
8035 .any(|entry| {
8036 entry.diagnostic.is_primary
8037 && !entry.range.is_empty()
8038 && entry.range.start == primary_range_start
8039 && entry.diagnostic.message == active_diagnostics.primary_message
8040 });
8041
8042 if is_valid != active_diagnostics.is_valid {
8043 active_diagnostics.is_valid = is_valid;
8044 let mut new_styles = HashMap::default();
8045 for (block_id, diagnostic) in &active_diagnostics.blocks {
8046 new_styles.insert(
8047 *block_id,
8048 diagnostic_block_renderer(diagnostic.clone(), is_valid),
8049 );
8050 }
8051 self.display_map
8052 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
8053 }
8054 }
8055 }
8056
8057 // fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
8058 // self.dismiss_diagnostics(cx);
8059 // self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
8060 // let buffer = self.buffer.read(cx).snapshot(cx);
8061
8062 // let mut primary_range = None;
8063 // let mut primary_message = None;
8064 // let mut group_end = Point::zero();
8065 // let diagnostic_group = buffer
8066 // .diagnostic_group::<Point>(group_id)
8067 // .map(|entry| {
8068 // if entry.range.end > group_end {
8069 // group_end = entry.range.end;
8070 // }
8071 // if entry.diagnostic.is_primary {
8072 // primary_range = Some(entry.range.clone());
8073 // primary_message = Some(entry.diagnostic.message.clone());
8074 // }
8075 // entry
8076 // })
8077 // .collect::<Vec<_>>();
8078 // let primary_range = primary_range?;
8079 // let primary_message = primary_message?;
8080 // let primary_range =
8081 // buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
8082
8083 // let blocks = display_map
8084 // .insert_blocks(
8085 // diagnostic_group.iter().map(|entry| {
8086 // let diagnostic = entry.diagnostic.clone();
8087 // let message_height = diagnostic.message.lines().count() as u8;
8088 // BlockProperties {
8089 // style: BlockStyle::Fixed,
8090 // position: buffer.anchor_after(entry.range.start),
8091 // height: message_height,
8092 // render: diagnostic_block_renderer(diagnostic, true),
8093 // disposition: BlockDisposition::Below,
8094 // }
8095 // }),
8096 // cx,
8097 // )
8098 // .into_iter()
8099 // .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
8100 // .collect();
8101
8102 // Some(ActiveDiagnosticGroup {
8103 // primary_range,
8104 // primary_message,
8105 // blocks,
8106 // is_valid: true,
8107 // })
8108 // });
8109 // self.active_diagnostics.is_some()
8110 // }
8111
8112 // fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
8113 // if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
8114 // self.display_map.update(cx, |display_map, cx| {
8115 // display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
8116 // });
8117 // cx.notify();
8118 // }
8119 // }
8120
8121 // pub fn set_selections_from_remote(
8122 // &mut self,
8123 // selections: Vec<Selection<Anchor>>,
8124 // pending_selection: Option<Selection<Anchor>>,
8125 // cx: &mut ViewContext<Self>,
8126 // ) {
8127 // let old_cursor_position = self.selections.newest_anchor().head();
8128 // self.selections.change_with(cx, |s| {
8129 // s.select_anchors(selections);
8130 // if let Some(pending_selection) = pending_selection {
8131 // s.set_pending(pending_selection, SelectMode::Character);
8132 // } else {
8133 // s.clear_pending();
8134 // }
8135 // });
8136 // self.selections_did_change(false, &old_cursor_position, cx);
8137 // }
8138
8139 fn push_to_selection_history(&mut self) {
8140 self.selection_history.push(SelectionHistoryEntry {
8141 selections: self.selections.disjoint_anchors(),
8142 select_next_state: self.select_next_state.clone(),
8143 select_prev_state: self.select_prev_state.clone(),
8144 add_selections_state: self.add_selections_state.clone(),
8145 });
8146 }
8147
8148 pub fn transact(
8149 &mut self,
8150 cx: &mut ViewContext<Self>,
8151 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
8152 ) -> Option<TransactionId> {
8153 self.start_transaction_at(Instant::now(), cx);
8154 update(self, cx);
8155 self.end_transaction_at(Instant::now(), cx)
8156 }
8157
8158 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
8159 todo!()
8160 // self.end_selection(cx);
8161 // if let Some(tx_id) = self
8162 // .buffer
8163 // .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
8164 // {
8165 // self.selection_history
8166 // .insert_transaction(tx_id, self.selections.disjoint_anchors());
8167 // }
8168 }
8169
8170 fn end_transaction_at(
8171 &mut self,
8172 now: Instant,
8173 cx: &mut ViewContext<Self>,
8174 ) -> Option<TransactionId> {
8175 todo!()
8176 // if let Some(tx_id) = self
8177 // .buffer
8178 // .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
8179 // {
8180 // if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
8181 // *end_selections = Some(self.selections.disjoint_anchors());
8182 // } else {
8183 // error!("unexpectedly ended a transaction that wasn't started by this editor");
8184 // }
8185
8186 // cx.emit(Event::Edited);
8187 // Some(tx_id)
8188 // } else {
8189 // None
8190 // }
8191 }
8192
8193 // pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
8194 // let mut fold_ranges = Vec::new();
8195
8196 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8197
8198 // let selections = self.selections.all_adjusted(cx);
8199 // for selection in selections {
8200 // let range = selection.range().sorted();
8201 // let buffer_start_row = range.start.row;
8202
8203 // for row in (0..=range.end.row).rev() {
8204 // let fold_range = display_map.foldable_range(row);
8205
8206 // if let Some(fold_range) = fold_range {
8207 // if fold_range.end.row >= buffer_start_row {
8208 // fold_ranges.push(fold_range);
8209 // if row <= range.start.row {
8210 // break;
8211 // }
8212 // }
8213 // }
8214 // }
8215 // }
8216
8217 // self.fold_ranges(fold_ranges, true, cx);
8218 // }
8219
8220 // pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
8221 // let buffer_row = fold_at.buffer_row;
8222 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8223
8224 // if let Some(fold_range) = display_map.foldable_range(buffer_row) {
8225 // let autoscroll = self
8226 // .selections
8227 // .all::<Point>(cx)
8228 // .iter()
8229 // .any(|selection| fold_range.overlaps(&selection.range()));
8230
8231 // self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
8232 // }
8233 // }
8234
8235 // pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
8236 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8237 // let buffer = &display_map.buffer_snapshot;
8238 // let selections = self.selections.all::<Point>(cx);
8239 // let ranges = selections
8240 // .iter()
8241 // .map(|s| {
8242 // let range = s.display_range(&display_map).sorted();
8243 // let mut start = range.start.to_point(&display_map);
8244 // let mut end = range.end.to_point(&display_map);
8245 // start.column = 0;
8246 // end.column = buffer.line_len(end.row);
8247 // start..end
8248 // })
8249 // .collect::<Vec<_>>();
8250
8251 // self.unfold_ranges(ranges, true, true, cx);
8252 // }
8253
8254 // pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
8255 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8256
8257 // let intersection_range = Point::new(unfold_at.buffer_row, 0)
8258 // ..Point::new(
8259 // unfold_at.buffer_row,
8260 // display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
8261 // );
8262
8263 // let autoscroll = self
8264 // .selections
8265 // .all::<Point>(cx)
8266 // .iter()
8267 // .any(|selection| selection.range().overlaps(&intersection_range));
8268
8269 // self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8270 // }
8271
8272 // pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8273 // let selections = self.selections.all::<Point>(cx);
8274 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8275 // let line_mode = self.selections.line_mode;
8276 // let ranges = selections.into_iter().map(|s| {
8277 // if line_mode {
8278 // let start = Point::new(s.start.row, 0);
8279 // let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8280 // start..end
8281 // } else {
8282 // s.start..s.end
8283 // }
8284 // });
8285 // self.fold_ranges(ranges, true, cx);
8286 // }
8287
8288 pub fn fold_ranges<T: ToOffset + Clone>(
8289 &mut self,
8290 ranges: impl IntoIterator<Item = Range<T>>,
8291 auto_scroll: bool,
8292 cx: &mut ViewContext<Self>,
8293 ) {
8294 let mut ranges = ranges.into_iter().peekable();
8295 if ranges.peek().is_some() {
8296 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8297
8298 if auto_scroll {
8299 self.request_autoscroll(Autoscroll::fit(), cx);
8300 }
8301
8302 cx.notify();
8303 }
8304 }
8305
8306 pub fn unfold_ranges<T: ToOffset + Clone>(
8307 &mut self,
8308 ranges: impl IntoIterator<Item = Range<T>>,
8309 inclusive: bool,
8310 auto_scroll: bool,
8311 cx: &mut ViewContext<Self>,
8312 ) {
8313 let mut ranges = ranges.into_iter().peekable();
8314 if ranges.peek().is_some() {
8315 self.display_map
8316 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8317 if auto_scroll {
8318 self.request_autoscroll(Autoscroll::fit(), cx);
8319 }
8320
8321 cx.notify();
8322 }
8323 }
8324
8325 // pub fn gutter_hover(
8326 // &mut self,
8327 // GutterHover { hovered }: &GutterHover,
8328 // cx: &mut ViewContext<Self>,
8329 // ) {
8330 // self.gutter_hovered = *hovered;
8331 // cx.notify();
8332 // }
8333
8334 // pub fn insert_blocks(
8335 // &mut self,
8336 // blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8337 // autoscroll: Option<Autoscroll>,
8338 // cx: &mut ViewContext<Self>,
8339 // ) -> Vec<BlockId> {
8340 // let blocks = self
8341 // .display_map
8342 // .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8343 // if let Some(autoscroll) = autoscroll {
8344 // self.request_autoscroll(autoscroll, cx);
8345 // }
8346 // blocks
8347 // }
8348
8349 // pub fn replace_blocks(
8350 // &mut self,
8351 // blocks: HashMap<BlockId, RenderBlock>,
8352 // autoscroll: Option<Autoscroll>,
8353 // cx: &mut ViewContext<Self>,
8354 // ) {
8355 // self.display_map
8356 // .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8357 // if let Some(autoscroll) = autoscroll {
8358 // self.request_autoscroll(autoscroll, cx);
8359 // }
8360 // }
8361
8362 pub fn remove_blocks(
8363 &mut self,
8364 block_ids: HashSet<BlockId>,
8365 autoscroll: Option<Autoscroll>,
8366 cx: &mut ViewContext<Self>,
8367 ) {
8368 self.display_map.update(cx, |display_map, cx| {
8369 display_map.remove_blocks(block_ids, cx)
8370 });
8371 if let Some(autoscroll) = autoscroll {
8372 self.request_autoscroll(autoscroll, cx);
8373 }
8374 }
8375
8376 // pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8377 // self.display_map
8378 // .update(cx, |map, cx| map.snapshot(cx))
8379 // .longest_row()
8380 // }
8381
8382 // pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8383 // self.display_map
8384 // .update(cx, |map, cx| map.snapshot(cx))
8385 // .max_point()
8386 // }
8387
8388 // pub fn text(&self, cx: &AppContext) -> String {
8389 // self.buffer.read(cx).read(cx).text()
8390 // }
8391
8392 // pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8393 // self.transact(cx, |this, cx| {
8394 // this.buffer
8395 // .read(cx)
8396 // .as_singleton()
8397 // .expect("you can only call set_text on editors for singleton buffers")
8398 // .update(cx, |buffer, cx| buffer.set_text(text, cx));
8399 // });
8400 // }
8401
8402 // pub fn display_text(&self, cx: &mut AppContext) -> String {
8403 // self.display_map
8404 // .update(cx, |map, cx| map.snapshot(cx))
8405 // .text()
8406 // }
8407
8408 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8409 let mut wrap_guides = smallvec::smallvec![];
8410
8411 if self.show_wrap_guides == Some(false) {
8412 return wrap_guides;
8413 }
8414
8415 let settings = self.buffer.read(cx).settings_at(0, cx);
8416 if settings.show_wrap_guides {
8417 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8418 wrap_guides.push((soft_wrap as usize, true));
8419 }
8420 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8421 }
8422
8423 wrap_guides
8424 }
8425
8426 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8427 let settings = self.buffer.read(cx).settings_at(0, cx);
8428 let mode = self
8429 .soft_wrap_mode_override
8430 .unwrap_or_else(|| settings.soft_wrap);
8431 match mode {
8432 language_settings::SoftWrap::None => SoftWrap::None,
8433 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8434 language_settings::SoftWrap::PreferredLineLength => {
8435 SoftWrap::Column(settings.preferred_line_length)
8436 }
8437 }
8438 }
8439
8440 pub fn set_soft_wrap_mode(
8441 &mut self,
8442 mode: language_settings::SoftWrap,
8443 cx: &mut ViewContext<Self>,
8444 ) {
8445 self.soft_wrap_mode_override = Some(mode);
8446 cx.notify();
8447 }
8448
8449 pub fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
8450 self.display_map
8451 .update(cx, |map, cx| map.set_wrap_width(width, cx))
8452 }
8453
8454 // pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8455 // if self.soft_wrap_mode_override.is_some() {
8456 // self.soft_wrap_mode_override.take();
8457 // } else {
8458 // let soft_wrap = match self.soft_wrap_mode(cx) {
8459 // SoftWrap::None => language_settings::SoftWrap::EditorWidth,
8460 // SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
8461 // };
8462 // self.soft_wrap_mode_override = Some(soft_wrap);
8463 // }
8464 // cx.notify();
8465 // }
8466
8467 // pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8468 // self.show_gutter = show_gutter;
8469 // cx.notify();
8470 // }
8471
8472 // pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8473 // self.show_wrap_guides = Some(show_gutter);
8474 // cx.notify();
8475 // }
8476
8477 // pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
8478 // if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8479 // if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8480 // cx.reveal_path(&file.abs_path(cx));
8481 // }
8482 // }
8483 // }
8484
8485 // pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
8486 // if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8487 // if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8488 // if let Some(path) = file.abs_path(cx).to_str() {
8489 // cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8490 // }
8491 // }
8492 // }
8493 // }
8494
8495 // pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
8496 // if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8497 // if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8498 // if let Some(path) = file.path().to_str() {
8499 // cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8500 // }
8501 // }
8502 // }
8503 // }
8504
8505 pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
8506 self.highlighted_rows = rows;
8507 }
8508
8509 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
8510 self.highlighted_rows.clone()
8511 }
8512
8513 pub fn highlight_background<T: 'static>(
8514 &mut self,
8515 ranges: Vec<Range<Anchor>>,
8516 color_fetcher: fn(&ThemeColors) -> Hsla,
8517 cx: &mut ViewContext<Self>,
8518 ) {
8519 self.background_highlights
8520 .insert(TypeId::of::<T>(), (color_fetcher, ranges));
8521 cx.notify();
8522 }
8523
8524 // pub fn highlight_inlay_background<T: 'static>(
8525 // &mut self,
8526 // ranges: Vec<InlayHighlight>,
8527 // color_fetcher: fn(&Theme) -> Color,
8528 // cx: &mut ViewContext<Self>,
8529 // ) {
8530 // // TODO: no actual highlights happen for inlays currently, find a way to do that
8531 // self.inlay_background_highlights
8532 // .insert(Some(TypeId::of::<T>()), (color_fetcher, ranges));
8533 // cx.notify();
8534 // }
8535
8536 // pub fn clear_background_highlights<T: 'static>(
8537 // &mut self,
8538 // cx: &mut ViewContext<Self>,
8539 // ) -> Option<BackgroundHighlight> {
8540 // let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
8541 // let inlay_highlights = self
8542 // .inlay_background_highlights
8543 // .remove(&Some(TypeId::of::<T>()));
8544 // if text_highlights.is_some() || inlay_highlights.is_some() {
8545 // cx.notify();
8546 // }
8547 // text_highlights
8548 // }
8549
8550 // #[cfg(feature = "test-support")]
8551 // pub fn all_text_background_highlights(
8552 // &mut self,
8553 // cx: &mut ViewContext<Self>,
8554 // ) -> Vec<(Range<DisplayPoint>, Color)> {
8555 // let snapshot = self.snapshot(cx);
8556 // let buffer = &snapshot.buffer_snapshot;
8557 // let start = buffer.anchor_before(0);
8558 // let end = buffer.anchor_after(buffer.len());
8559 // let theme = theme::current(cx);
8560 // self.background_highlights_in_range(start..end, &snapshot, theme.as_ref())
8561 // }
8562
8563 // fn document_highlights_for_position<'a>(
8564 // &'a self,
8565 // position: Anchor,
8566 // buffer: &'a MultiBufferSnapshot,
8567 // ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
8568 // let read_highlights = self
8569 // .background_highlights
8570 // .get(&TypeId::of::<DocumentHighlightRead>())
8571 // .map(|h| &h.1);
8572 // let write_highlights = self
8573 // .background_highlights
8574 // .get(&TypeId::of::<DocumentHighlightWrite>())
8575 // .map(|h| &h.1);
8576 // let left_position = position.bias_left(buffer);
8577 // let right_position = position.bias_right(buffer);
8578 // read_highlights
8579 // .into_iter()
8580 // .chain(write_highlights)
8581 // .flat_map(move |ranges| {
8582 // let start_ix = match ranges.binary_search_by(|probe| {
8583 // let cmp = probe.end.cmp(&left_position, buffer);
8584 // if cmp.is_ge() {
8585 // Ordering::Greater
8586 // } else {
8587 // Ordering::Less
8588 // }
8589 // }) {
8590 // Ok(i) | Err(i) => i,
8591 // };
8592
8593 // let right_position = right_position.clone();
8594 // ranges[start_ix..]
8595 // .iter()
8596 // .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
8597 // })
8598 // }
8599
8600 pub fn background_highlights_in_range(
8601 &self,
8602 search_range: Range<Anchor>,
8603 display_snapshot: &DisplaySnapshot,
8604 theme: &ThemeColors,
8605 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
8606 let mut results = Vec::new();
8607 for (color_fetcher, ranges) in self.background_highlights.values() {
8608 let color = color_fetcher(theme);
8609 let start_ix = match ranges.binary_search_by(|probe| {
8610 let cmp = probe
8611 .end
8612 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8613 if cmp.is_gt() {
8614 Ordering::Greater
8615 } else {
8616 Ordering::Less
8617 }
8618 }) {
8619 Ok(i) | Err(i) => i,
8620 };
8621 for range in &ranges[start_ix..] {
8622 if range
8623 .start
8624 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8625 .is_ge()
8626 {
8627 break;
8628 }
8629
8630 let start = range.start.to_display_point(&display_snapshot);
8631 let end = range.end.to_display_point(&display_snapshot);
8632 results.push((start..end, color))
8633 }
8634 }
8635 results
8636 }
8637
8638 // pub fn background_highlight_row_ranges<T: 'static>(
8639 // &self,
8640 // search_range: Range<Anchor>,
8641 // display_snapshot: &DisplaySnapshot,
8642 // count: usize,
8643 // ) -> Vec<RangeInclusive<DisplayPoint>> {
8644 // let mut results = Vec::new();
8645 // let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
8646 // return vec![];
8647 // };
8648
8649 // let start_ix = match ranges.binary_search_by(|probe| {
8650 // let cmp = probe
8651 // .end
8652 // .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8653 // if cmp.is_gt() {
8654 // Ordering::Greater
8655 // } else {
8656 // Ordering::Less
8657 // }
8658 // }) {
8659 // Ok(i) | Err(i) => i,
8660 // };
8661 // let mut push_region = |start: Option<Point>, end: Option<Point>| {
8662 // if let (Some(start_display), Some(end_display)) = (start, end) {
8663 // results.push(
8664 // start_display.to_display_point(display_snapshot)
8665 // ..=end_display.to_display_point(display_snapshot),
8666 // );
8667 // }
8668 // };
8669 // let mut start_row: Option<Point> = None;
8670 // let mut end_row: Option<Point> = None;
8671 // if ranges.len() > count {
8672 // return Vec::new();
8673 // }
8674 // for range in &ranges[start_ix..] {
8675 // if range
8676 // .start
8677 // .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8678 // .is_ge()
8679 // {
8680 // break;
8681 // }
8682 // let end = range.end.to_point(&display_snapshot.buffer_snapshot);
8683 // if let Some(current_row) = &end_row {
8684 // if end.row == current_row.row {
8685 // continue;
8686 // }
8687 // }
8688 // let start = range.start.to_point(&display_snapshot.buffer_snapshot);
8689 // if start_row.is_none() {
8690 // assert_eq!(end_row, None);
8691 // start_row = Some(start);
8692 // end_row = Some(end);
8693 // continue;
8694 // }
8695 // if let Some(current_end) = end_row.as_mut() {
8696 // if start.row > current_end.row + 1 {
8697 // push_region(start_row, end_row);
8698 // start_row = Some(start);
8699 // end_row = Some(end);
8700 // } else {
8701 // // Merge two hunks.
8702 // *current_end = end;
8703 // }
8704 // } else {
8705 // unreachable!();
8706 // }
8707 // }
8708 // // We might still have a hunk that was not rendered (if there was a search hit on the last line)
8709 // push_region(start_row, end_row);
8710 // results
8711 // }
8712
8713 // pub fn highlight_text<T: 'static>(
8714 // &mut self,
8715 // ranges: Vec<Range<Anchor>>,
8716 // style: HighlightStyle,
8717 // cx: &mut ViewContext<Self>,
8718 // ) {
8719 // self.display_map.update(cx, |map, _| {
8720 // map.highlight_text(TypeId::of::<T>(), ranges, style)
8721 // });
8722 // cx.notify();
8723 // }
8724
8725 // pub fn highlight_inlays<T: 'static>(
8726 // &mut self,
8727 // highlights: Vec<InlayHighlight>,
8728 // style: HighlightStyle,
8729 // cx: &mut ViewContext<Self>,
8730 // ) {
8731 // self.display_map.update(cx, |map, _| {
8732 // map.highlight_inlays(TypeId::of::<T>(), highlights, style)
8733 // });
8734 // cx.notify();
8735 // }
8736
8737 // pub fn text_highlights<'a, T: 'static>(
8738 // &'a self,
8739 // cx: &'a AppContext,
8740 // ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
8741 // self.display_map.read(cx).text_highlights(TypeId::of::<T>())
8742 // }
8743
8744 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
8745 let cleared = self
8746 .display_map
8747 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
8748 if cleared {
8749 cx.notify();
8750 }
8751 }
8752
8753 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
8754 self.blink_manager.read(cx).visible() && self.focus_handle.is_focused(cx)
8755 }
8756
8757 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
8758 cx.notify();
8759 }
8760
8761 fn on_buffer_event(
8762 &mut self,
8763 multibuffer: Model<MultiBuffer>,
8764 event: &multi_buffer::Event,
8765 cx: &mut ViewContext<Self>,
8766 ) {
8767 match event {
8768 multi_buffer::Event::Edited {
8769 sigleton_buffer_edited,
8770 } => {
8771 self.refresh_active_diagnostics(cx);
8772 self.refresh_code_actions(cx);
8773 if self.has_active_copilot_suggestion(cx) {
8774 self.update_visible_copilot_suggestion(cx);
8775 }
8776 cx.emit(Event::BufferEdited);
8777
8778 if *sigleton_buffer_edited {
8779 if let Some(project) = &self.project {
8780 let project = project.read(cx);
8781 let languages_affected = multibuffer
8782 .read(cx)
8783 .all_buffers()
8784 .into_iter()
8785 .filter_map(|buffer| {
8786 let buffer = buffer.read(cx);
8787 let language = buffer.language()?;
8788 if project.is_local()
8789 && project.language_servers_for_buffer(buffer, cx).count() == 0
8790 {
8791 None
8792 } else {
8793 Some(language)
8794 }
8795 })
8796 .cloned()
8797 .collect::<HashSet<_>>();
8798 if !languages_affected.is_empty() {
8799 self.refresh_inlay_hints(
8800 InlayHintRefreshReason::BufferEdited(languages_affected),
8801 cx,
8802 );
8803 }
8804 }
8805 }
8806 }
8807 multi_buffer::Event::ExcerptsAdded {
8808 buffer,
8809 predecessor,
8810 excerpts,
8811 } => {
8812 cx.emit(Event::ExcerptsAdded {
8813 buffer: buffer.clone(),
8814 predecessor: *predecessor,
8815 excerpts: excerpts.clone(),
8816 });
8817 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
8818 }
8819 multi_buffer::Event::ExcerptsRemoved { ids } => {
8820 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
8821 cx.emit(Event::ExcerptsRemoved { ids: ids.clone() })
8822 }
8823 multi_buffer::Event::Reparsed => cx.emit(Event::Reparsed),
8824 multi_buffer::Event::DirtyChanged => cx.emit(Event::DirtyChanged),
8825 multi_buffer::Event::Saved => cx.emit(Event::Saved),
8826 multi_buffer::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
8827 multi_buffer::Event::Reloaded => cx.emit(Event::TitleChanged),
8828 multi_buffer::Event::DiffBaseChanged => cx.emit(Event::DiffBaseChanged),
8829 multi_buffer::Event::Closed => cx.emit(Event::Closed),
8830 multi_buffer::Event::DiagnosticsUpdated => {
8831 self.refresh_active_diagnostics(cx);
8832 }
8833 _ => {}
8834 };
8835 }
8836
8837 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
8838 cx.notify();
8839 }
8840
8841 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
8842 self.refresh_copilot_suggestions(true, cx);
8843 self.refresh_inlay_hints(
8844 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
8845 self.selections.newest_anchor().head(),
8846 &self.buffer.read(cx).snapshot(cx),
8847 cx,
8848 )),
8849 cx,
8850 );
8851 }
8852
8853 // pub fn set_searchable(&mut self, searchable: bool) {
8854 // self.searchable = searchable;
8855 // }
8856
8857 // pub fn searchable(&self) -> bool {
8858 // self.searchable
8859 // }
8860
8861 // fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
8862 // let active_item = workspace.active_item(cx);
8863 // let editor_handle = if let Some(editor) = active_item
8864 // .as_ref()
8865 // .and_then(|item| item.act_as::<Self>(cx))
8866 // {
8867 // editor
8868 // } else {
8869 // cx.propagate();
8870 // return;
8871 // };
8872
8873 // let editor = editor_handle.read(cx);
8874 // let buffer = editor.buffer.read(cx);
8875 // if buffer.is_singleton() {
8876 // cx.propagate();
8877 // return;
8878 // }
8879
8880 // let mut new_selections_by_buffer = HashMap::default();
8881 // for selection in editor.selections.all::<usize>(cx) {
8882 // for (buffer, mut range, _) in
8883 // buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
8884 // {
8885 // if selection.reversed {
8886 // mem::swap(&mut range.start, &mut range.end);
8887 // }
8888 // new_selections_by_buffer
8889 // .entry(buffer)
8890 // .or_insert(Vec::new())
8891 // .push(range)
8892 // }
8893 // }
8894
8895 // editor_handle.update(cx, |editor, cx| {
8896 // editor.push_to_nav_history(editor.selections.newest_anchor().head(), None, cx);
8897 // });
8898 // let pane = workspace.active_pane().clone();
8899 // pane.update(cx, |pane, _| pane.disable_history());
8900
8901 // // We defer the pane interaction because we ourselves are a workspace item
8902 // // and activating a new item causes the pane to call a method on us reentrantly,
8903 // // which panics if we're on the stack.
8904 // cx.defer(move |workspace, cx| {
8905 // for (buffer, ranges) in new_selections_by_buffer.into_iter() {
8906 // let editor = workspace.open_project_item::<Self>(buffer, cx);
8907 // editor.update(cx, |editor, cx| {
8908 // editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8909 // s.select_ranges(ranges);
8910 // });
8911 // });
8912 // }
8913
8914 // pane.update(cx, |pane, _| pane.enable_history());
8915 // });
8916 // }
8917
8918 // fn jump(
8919 // workspace: &mut Workspace,
8920 // path: ProjectPath,
8921 // position: Point,
8922 // anchor: language::Anchor,
8923 // cx: &mut ViewContext<Workspace>,
8924 // ) {
8925 // let editor = workspace.open_path(path, None, true, cx);
8926 // cx.spawn(|_, mut cx| async move {
8927 // let editor = editor
8928 // .await?
8929 // .downcast::<Editor>()
8930 // .ok_or_else(|| anyhow!("opened item was not an editor"))?
8931 // .downgrade();
8932 // editor.update(&mut cx, |editor, cx| {
8933 // let buffer = editor
8934 // .buffer()
8935 // .read(cx)
8936 // .as_singleton()
8937 // .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
8938 // let buffer = buffer.read(cx);
8939 // let cursor = if buffer.can_resolve(&anchor) {
8940 // language::ToPoint::to_point(&anchor, buffer)
8941 // } else {
8942 // buffer.clip_point(position, Bias::Left)
8943 // };
8944
8945 // let nav_history = editor.nav_history.take();
8946 // editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8947 // s.select_ranges([cursor..cursor]);
8948 // });
8949 // editor.nav_history = nav_history;
8950
8951 // anyhow::Ok(())
8952 // })??;
8953
8954 // anyhow::Ok(())
8955 // })
8956 // .detach_and_log_err(cx);
8957 // }
8958
8959 // fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
8960 // let snapshot = self.buffer.read(cx).read(cx);
8961 // let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
8962 // Some(
8963 // ranges
8964 // .iter()
8965 // .map(move |range| {
8966 // range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
8967 // })
8968 // .collect(),
8969 // )
8970 // }
8971
8972 // fn selection_replacement_ranges(
8973 // &self,
8974 // range: Range<OffsetUtf16>,
8975 // cx: &AppContext,
8976 // ) -> Vec<Range<OffsetUtf16>> {
8977 // let selections = self.selections.all::<OffsetUtf16>(cx);
8978 // let newest_selection = selections
8979 // .iter()
8980 // .max_by_key(|selection| selection.id)
8981 // .unwrap();
8982 // let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
8983 // let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
8984 // let snapshot = self.buffer.read(cx).read(cx);
8985 // selections
8986 // .into_iter()
8987 // .map(|mut selection| {
8988 // selection.start.0 =
8989 // (selection.start.0 as isize).saturating_add(start_delta) as usize;
8990 // selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
8991 // snapshot.clip_offset_utf16(selection.start, Bias::Left)
8992 // ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
8993 // })
8994 // .collect()
8995 // }
8996
8997 fn report_copilot_event(
8998 &self,
8999 suggestion_id: Option<String>,
9000 suggestion_accepted: bool,
9001 cx: &AppContext,
9002 ) {
9003 let Some(project) = &self.project else { return };
9004
9005 // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
9006 let file_extension = self
9007 .buffer
9008 .read(cx)
9009 .as_singleton()
9010 .and_then(|b| b.read(cx).file())
9011 .and_then(|file| Path::new(file.file_name(cx)).extension())
9012 .and_then(|e| e.to_str())
9013 .map(|a| a.to_string());
9014
9015 let telemetry = project.read(cx).client().telemetry().clone();
9016 let telemetry_settings = *TelemetrySettings::get_global(cx);
9017
9018 let event = ClickhouseEvent::Copilot {
9019 suggestion_id,
9020 suggestion_accepted,
9021 file_extension,
9022 };
9023 telemetry.report_clickhouse_event(event, telemetry_settings);
9024 }
9025
9026 #[cfg(any(test, feature = "test-support"))]
9027 fn report_editor_event(
9028 &self,
9029 _operation: &'static str,
9030 _file_extension: Option<String>,
9031 _cx: &AppContext,
9032 ) {
9033 }
9034
9035 #[cfg(not(any(test, feature = "test-support")))]
9036 fn report_editor_event(
9037 &self,
9038 operation: &'static str,
9039 file_extension: Option<String>,
9040 cx: &AppContext,
9041 ) {
9042 let Some(project) = &self.project else { return };
9043
9044 // If None, we are in a file without an extension
9045 let file = self
9046 .buffer
9047 .read(cx)
9048 .as_singleton()
9049 .and_then(|b| b.read(cx).file());
9050 let file_extension = file_extension.or(file
9051 .as_ref()
9052 .and_then(|file| Path::new(file.file_name(cx)).extension())
9053 .and_then(|e| e.to_str())
9054 .map(|a| a.to_string()));
9055
9056 let vim_mode = cx
9057 .global::<SettingsStore>()
9058 .raw_user_settings()
9059 .get("vim_mode")
9060 == Some(&serde_json::Value::Bool(true));
9061 let telemetry_settings = *TelemetrySettings::get_global(cx);
9062 let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
9063 let copilot_enabled_for_language = self
9064 .buffer
9065 .read(cx)
9066 .settings_at(0, cx)
9067 .show_copilot_suggestions;
9068
9069 let telemetry = project.read(cx).client().telemetry().clone();
9070 let event = ClickhouseEvent::Editor {
9071 file_extension,
9072 vim_mode,
9073 operation,
9074 copilot_enabled,
9075 copilot_enabled_for_language,
9076 };
9077 telemetry.report_clickhouse_event(event, telemetry_settings)
9078 }
9079
9080 // /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
9081 // /// with each line being an array of {text, highlight} objects.
9082 // fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
9083 // let Some(buffer) = self.buffer.read(cx).as_singleton() else {
9084 // return;
9085 // };
9086
9087 // #[derive(Serialize)]
9088 // struct Chunk<'a> {
9089 // text: String,
9090 // highlight: Option<&'a str>,
9091 // }
9092
9093 // let snapshot = buffer.read(cx).snapshot();
9094 // let range = self
9095 // .selected_text_range(cx)
9096 // .and_then(|selected_range| {
9097 // if selected_range.is_empty() {
9098 // None
9099 // } else {
9100 // Some(selected_range)
9101 // }
9102 // })
9103 // .unwrap_or_else(|| 0..snapshot.len());
9104
9105 // let chunks = snapshot.chunks(range, true);
9106 // let mut lines = Vec::new();
9107 // let mut line: VecDeque<Chunk> = VecDeque::new();
9108
9109 // let theme = &theme::current(cx).editor.syntax;
9110
9111 // for chunk in chunks {
9112 // let highlight = chunk.syntax_highlight_id.and_then(|id| id.name(theme));
9113 // let mut chunk_lines = chunk.text.split("\n").peekable();
9114 // while let Some(text) = chunk_lines.next() {
9115 // let mut merged_with_last_token = false;
9116 // if let Some(last_token) = line.back_mut() {
9117 // if last_token.highlight == highlight {
9118 // last_token.text.push_str(text);
9119 // merged_with_last_token = true;
9120 // }
9121 // }
9122
9123 // if !merged_with_last_token {
9124 // line.push_back(Chunk {
9125 // text: text.into(),
9126 // highlight,
9127 // });
9128 // }
9129
9130 // if chunk_lines.peek().is_some() {
9131 // if line.len() > 1 && line.front().unwrap().text.is_empty() {
9132 // line.pop_front();
9133 // }
9134 // if line.len() > 1 && line.back().unwrap().text.is_empty() {
9135 // line.pop_back();
9136 // }
9137
9138 // lines.push(mem::take(&mut line));
9139 // }
9140 // }
9141 // }
9142
9143 // let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
9144 // return;
9145 // };
9146 // cx.write_to_clipboard(ClipboardItem::new(lines));
9147 // }
9148
9149 // pub fn inlay_hint_cache(&self) -> &InlayHintCache {
9150 // &self.inlay_hint_cache
9151 // }
9152
9153 // pub fn replay_insert_event(
9154 // &mut self,
9155 // text: &str,
9156 // relative_utf16_range: Option<Range<isize>>,
9157 // cx: &mut ViewContext<Self>,
9158 // ) {
9159 // if !self.input_enabled {
9160 // cx.emit(Event::InputIgnored { text: text.into() });
9161 // return;
9162 // }
9163 // if let Some(relative_utf16_range) = relative_utf16_range {
9164 // let selections = self.selections.all::<OffsetUtf16>(cx);
9165 // self.change_selections(None, cx, |s| {
9166 // let new_ranges = selections.into_iter().map(|range| {
9167 // let start = OffsetUtf16(
9168 // range
9169 // .head()
9170 // .0
9171 // .saturating_add_signed(relative_utf16_range.start),
9172 // );
9173 // let end = OffsetUtf16(
9174 // range
9175 // .head()
9176 // .0
9177 // .saturating_add_signed(relative_utf16_range.end),
9178 // );
9179 // start..end
9180 // });
9181 // s.select_ranges(new_ranges);
9182 // });
9183 // }
9184
9185 // self.handle_input(text, cx);
9186 // }
9187
9188 // pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
9189 // let Some(project) = self.project.as_ref() else {
9190 // return false;
9191 // };
9192 // let project = project.read(cx);
9193
9194 // let mut supports = false;
9195 // self.buffer().read(cx).for_each_buffer(|buffer| {
9196 // if !supports {
9197 // supports = project
9198 // .language_servers_for_buffer(buffer.read(cx), cx)
9199 // .any(
9200 // |(_, server)| match server.capabilities().inlay_hint_provider {
9201 // Some(lsp::OneOf::Left(enabled)) => enabled,
9202 // Some(lsp::OneOf::Right(_)) => true,
9203 // None => false,
9204 // },
9205 // )
9206 // }
9207 // });
9208 // supports
9209 // }
9210}
9211
9212pub trait CollaborationHub {
9213 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
9214 fn user_participant_indices<'a>(
9215 &self,
9216 cx: &'a AppContext,
9217 ) -> &'a HashMap<u64, ParticipantIndex>;
9218}
9219
9220impl CollaborationHub for Model<Project> {
9221 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
9222 self.read(cx).collaborators()
9223 }
9224
9225 fn user_participant_indices<'a>(
9226 &self,
9227 cx: &'a AppContext,
9228 ) -> &'a HashMap<u64, ParticipantIndex> {
9229 self.read(cx).user_store().read(cx).participant_indices()
9230 }
9231}
9232
9233fn inlay_hint_settings(
9234 location: Anchor,
9235 snapshot: &MultiBufferSnapshot,
9236 cx: &mut ViewContext<'_, Editor>,
9237) -> InlayHintSettings {
9238 let file = snapshot.file_at(location);
9239 let language = snapshot.language_at(location);
9240 let settings = all_language_settings(file, cx);
9241 settings
9242 .language(language.map(|l| l.name()).as_deref())
9243 .inlay_hints
9244}
9245
9246fn consume_contiguous_rows(
9247 contiguous_row_selections: &mut Vec<Selection<Point>>,
9248 selection: &Selection<Point>,
9249 display_map: &DisplaySnapshot,
9250 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
9251) -> (u32, u32) {
9252 contiguous_row_selections.push(selection.clone());
9253 let start_row = selection.start.row;
9254 let mut end_row = ending_row(selection, display_map);
9255
9256 while let Some(next_selection) = selections.peek() {
9257 if next_selection.start.row <= end_row {
9258 end_row = ending_row(next_selection, display_map);
9259 contiguous_row_selections.push(selections.next().unwrap().clone());
9260 } else {
9261 break;
9262 }
9263 }
9264 (start_row, end_row)
9265}
9266
9267fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
9268 if next_selection.end.column > 0 || next_selection.is_empty() {
9269 display_map.next_line_boundary(next_selection.end).0.row + 1
9270 } else {
9271 next_selection.end.row
9272 }
9273}
9274
9275impl EditorSnapshot {
9276 pub fn remote_selections_in_range<'a>(
9277 &'a self,
9278 range: &'a Range<Anchor>,
9279 collaboration_hub: &dyn CollaborationHub,
9280 cx: &'a AppContext,
9281 ) -> impl 'a + Iterator<Item = RemoteSelection> {
9282 let participant_indices = collaboration_hub.user_participant_indices(cx);
9283 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
9284 let collaborators_by_replica_id = collaborators_by_peer_id
9285 .iter()
9286 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
9287 .collect::<HashMap<_, _>>();
9288 self.buffer_snapshot
9289 .remote_selections_in_range(range)
9290 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
9291 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
9292 let participant_index = participant_indices.get(&collaborator.user_id).copied();
9293 Some(RemoteSelection {
9294 replica_id,
9295 selection,
9296 cursor_shape,
9297 line_mode,
9298 participant_index,
9299 peer_id: collaborator.peer_id,
9300 })
9301 })
9302 }
9303
9304 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
9305 self.display_snapshot.buffer_snapshot.language_at(position)
9306 }
9307
9308 pub fn is_focused(&self) -> bool {
9309 self.is_focused
9310 }
9311
9312 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
9313 self.placeholder_text.as_ref()
9314 }
9315
9316 pub fn scroll_position(&self) -> gpui::Point<f32> {
9317 self.scroll_anchor.scroll_position(&self.display_snapshot)
9318 }
9319}
9320
9321impl Deref for EditorSnapshot {
9322 type Target = DisplaySnapshot;
9323
9324 fn deref(&self) -> &Self::Target {
9325 &self.display_snapshot
9326 }
9327}
9328
9329#[derive(Clone, Debug, PartialEq, Eq)]
9330pub enum Event {
9331 InputIgnored {
9332 text: Arc<str>,
9333 },
9334 InputHandled {
9335 utf16_range_to_replace: Option<Range<isize>>,
9336 text: Arc<str>,
9337 },
9338 ExcerptsAdded {
9339 buffer: Model<Buffer>,
9340 predecessor: ExcerptId,
9341 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
9342 },
9343 ExcerptsRemoved {
9344 ids: Vec<ExcerptId>,
9345 },
9346 BufferEdited,
9347 Edited,
9348 Reparsed,
9349 Focused,
9350 Blurred,
9351 DirtyChanged,
9352 Saved,
9353 TitleChanged,
9354 DiffBaseChanged,
9355 SelectionsChanged {
9356 local: bool,
9357 },
9358 ScrollPositionChanged {
9359 local: bool,
9360 autoscroll: bool,
9361 },
9362 Closed,
9363}
9364
9365pub struct EditorFocused(pub View<Editor>);
9366pub struct EditorBlurred(pub View<Editor>);
9367pub struct EditorReleased(pub WeakView<Editor>);
9368
9369// impl Entity for Editor {
9370// type Event = Event;
9371
9372// fn release(&mut self, cx: &mut AppContext) {
9373// cx.emit_global(EditorReleased(self.handle.clone()));
9374// }
9375// }
9376//
9377impl EventEmitter for Editor {
9378 type Event = Event;
9379}
9380
9381impl Render for Editor {
9382 type Element = EditorElement;
9383
9384 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
9385 let settings = ThemeSettings::get_global(cx);
9386 let text_style = TextStyle {
9387 color: cx.theme().colors().text,
9388 font_family: settings.buffer_font.family.clone(),
9389 font_features: settings.buffer_font.features,
9390 font_size: settings.buffer_font_size.into(),
9391 font_weight: FontWeight::NORMAL,
9392 font_style: FontStyle::Normal,
9393 line_height: Default::default(),
9394 underline: None,
9395 };
9396 EditorElement::new(EditorStyle {
9397 background: cx.theme().colors().editor_background,
9398 local_player: cx.theme().players().local(),
9399 text: text_style,
9400 line_height_scalar: settings.buffer_line_height.value(),
9401 scrollbar_width: px(12.),
9402 })
9403 }
9404}
9405
9406// impl View for Editor {
9407// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
9408// let style = self.style(cx);
9409// let font_changed = self.display_map.update(cx, |map, cx| {
9410// map.set_fold_ellipses_color(style.folds.ellipses.text_color);
9411// map.set_font_with_size(style.text.font_id, style.text.font_size, cx)
9412// });
9413
9414// if font_changed {
9415// cx.defer(move |editor, cx: &mut ViewContext<Editor>| {
9416// hide_hover(editor, cx);
9417// hide_link_definition(editor, cx);
9418// });
9419// }
9420
9421// Stack::new()
9422// .with_child(EditorElement::new(style.clone()))
9423// .with_child(ChildView::new(&self.mouse_context_menu, cx))
9424// .into_any()
9425// }
9426
9427// fn ui_name() -> &'static str {
9428// "Editor"
9429// }
9430
9431// fn focus_in(&mut self, focused: AnyView, cx: &mut ViewContext<Self>) {
9432// if cx.is_self_focused() {
9433// let focused_event = EditorFocused(cx.handle());
9434// cx.emit(Event::Focused);
9435// cx.emit_global(focused_event);
9436// }
9437// if let Some(rename) = self.pending_rename.as_ref() {
9438// cx.focus(&rename.editor);
9439// } else if cx.is_self_focused() || !focused.is::<Editor>() {
9440// if !self.focused {
9441// self.blink_manager.update(cx, BlinkManager::enable);
9442// }
9443// self.focused = true;
9444// self.buffer.update(cx, |buffer, cx| {
9445// buffer.finalize_last_transaction(cx);
9446// if self.leader_peer_id.is_none() {
9447// buffer.set_active_selections(
9448// &self.selections.disjoint_anchors(),
9449// self.selections.line_mode,
9450// self.cursor_shape,
9451// cx,
9452// );
9453// }
9454// });
9455// }
9456// }
9457
9458// fn focus_out(&mut self, _: AnyView, cx: &mut ViewContext<Self>) {
9459// let blurred_event = EditorBlurred(cx.handle());
9460// cx.emit_global(blurred_event);
9461// self.focused = false;
9462// self.blink_manager.update(cx, BlinkManager::disable);
9463// self.buffer
9464// .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
9465// self.hide_context_menu(cx);
9466// hide_hover(self, cx);
9467// cx.emit(Event::Blurred);
9468// cx.notify();
9469// }
9470
9471// fn modifiers_changed(
9472// &mut self,
9473// event: &gpui::platform::ModifiersChangedEvent,
9474// cx: &mut ViewContext<Self>,
9475// ) -> bool {
9476// let pending_selection = self.has_pending_selection();
9477
9478// if let Some(point) = &self.link_go_to_definition_state.last_trigger_point {
9479// if event.cmd && !pending_selection {
9480// let point = point.clone();
9481// let snapshot = self.snapshot(cx);
9482// let kind = point.definition_kind(event.shift);
9483
9484// show_link_definition(kind, self, point, snapshot, cx);
9485// return false;
9486// }
9487// }
9488
9489// {
9490// if self.link_go_to_definition_state.symbol_range.is_some()
9491// || !self.link_go_to_definition_state.definitions.is_empty()
9492// {
9493// self.link_go_to_definition_state.symbol_range.take();
9494// self.link_go_to_definition_state.definitions.clear();
9495// cx.notify();
9496// }
9497
9498// self.link_go_to_definition_state.task = None;
9499
9500// self.clear_highlights::<LinkGoToDefinitionState>(cx);
9501// }
9502
9503// false
9504// }
9505//
9506// fn text_for_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<String> {
9507// Some(
9508// self.buffer
9509// .read(cx)
9510// .read(cx)
9511// .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
9512// .collect(),
9513// )
9514// }
9515
9516// fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
9517// // Prevent the IME menu from appearing when holding down an alphabetic key
9518// // while input is disabled.
9519// if !self.input_enabled {
9520// return None;
9521// }
9522
9523// let range = self.selections.newest::<OffsetUtf16>(cx).range();
9524// Some(range.start.0..range.end.0)
9525// }
9526
9527// fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
9528// let snapshot = self.buffer.read(cx).read(cx);
9529// let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
9530// Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
9531// }
9532
9533// fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
9534// self.clear_highlights::<InputComposition>(cx);
9535// self.ime_transaction.take();
9536// }
9537
9538// fn replace_text_in_range(
9539// &mut self,
9540// range_utf16: Option<Range<usize>>,
9541// text: &str,
9542// cx: &mut ViewContext<Self>,
9543// ) {
9544// if !self.input_enabled {
9545// cx.emit(Event::InputIgnored { text: text.into() });
9546// return;
9547// }
9548
9549// self.transact(cx, |this, cx| {
9550// let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
9551// let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9552// Some(this.selection_replacement_ranges(range_utf16, cx))
9553// } else {
9554// this.marked_text_ranges(cx)
9555// };
9556
9557// let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
9558// let newest_selection_id = this.selections.newest_anchor().id;
9559// this.selections
9560// .all::<OffsetUtf16>(cx)
9561// .iter()
9562// .zip(ranges_to_replace.iter())
9563// .find_map(|(selection, range)| {
9564// if selection.id == newest_selection_id {
9565// Some(
9566// (range.start.0 as isize - selection.head().0 as isize)
9567// ..(range.end.0 as isize - selection.head().0 as isize),
9568// )
9569// } else {
9570// None
9571// }
9572// })
9573// });
9574
9575// cx.emit(Event::InputHandled {
9576// utf16_range_to_replace: range_to_replace,
9577// text: text.into(),
9578// });
9579
9580// if let Some(new_selected_ranges) = new_selected_ranges {
9581// this.change_selections(None, cx, |selections| {
9582// selections.select_ranges(new_selected_ranges)
9583// });
9584// }
9585
9586// this.handle_input(text, cx);
9587// });
9588
9589// if let Some(transaction) = self.ime_transaction {
9590// self.buffer.update(cx, |buffer, cx| {
9591// buffer.group_until_transaction(transaction, cx);
9592// });
9593// }
9594
9595// self.unmark_text(cx);
9596// }
9597
9598// fn replace_and_mark_text_in_range(
9599// &mut self,
9600// range_utf16: Option<Range<usize>>,
9601// text: &str,
9602// new_selected_range_utf16: Option<Range<usize>>,
9603// cx: &mut ViewContext<Self>,
9604// ) {
9605// if !self.input_enabled {
9606// cx.emit(Event::InputIgnored { text: text.into() });
9607// return;
9608// }
9609
9610// let transaction = self.transact(cx, |this, cx| {
9611// let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
9612// let snapshot = this.buffer.read(cx).read(cx);
9613// if let Some(relative_range_utf16) = range_utf16.as_ref() {
9614// for marked_range in &mut marked_ranges {
9615// marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
9616// marked_range.start.0 += relative_range_utf16.start;
9617// marked_range.start =
9618// snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
9619// marked_range.end =
9620// snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
9621// }
9622// }
9623// Some(marked_ranges)
9624// } else if let Some(range_utf16) = range_utf16 {
9625// let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9626// Some(this.selection_replacement_ranges(range_utf16, cx))
9627// } else {
9628// None
9629// };
9630
9631// let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
9632// let newest_selection_id = this.selections.newest_anchor().id;
9633// this.selections
9634// .all::<OffsetUtf16>(cx)
9635// .iter()
9636// .zip(ranges_to_replace.iter())
9637// .find_map(|(selection, range)| {
9638// if selection.id == newest_selection_id {
9639// Some(
9640// (range.start.0 as isize - selection.head().0 as isize)
9641// ..(range.end.0 as isize - selection.head().0 as isize),
9642// )
9643// } else {
9644// None
9645// }
9646// })
9647// });
9648
9649// cx.emit(Event::InputHandled {
9650// utf16_range_to_replace: range_to_replace,
9651// text: text.into(),
9652// });
9653
9654// if let Some(ranges) = ranges_to_replace {
9655// this.change_selections(None, cx, |s| s.select_ranges(ranges));
9656// }
9657
9658// let marked_ranges = {
9659// let snapshot = this.buffer.read(cx).read(cx);
9660// this.selections
9661// .disjoint_anchors()
9662// .iter()
9663// .map(|selection| {
9664// selection.start.bias_left(&*snapshot)..selection.end.bias_right(&*snapshot)
9665// })
9666// .collect::<Vec<_>>()
9667// };
9668
9669// if text.is_empty() {
9670// this.unmark_text(cx);
9671// } else {
9672// this.highlight_text::<InputComposition>(
9673// marked_ranges.clone(),
9674// this.style(cx).composition_mark,
9675// cx,
9676// );
9677// }
9678
9679// this.handle_input(text, cx);
9680
9681// if let Some(new_selected_range) = new_selected_range_utf16 {
9682// let snapshot = this.buffer.read(cx).read(cx);
9683// let new_selected_ranges = marked_ranges
9684// .into_iter()
9685// .map(|marked_range| {
9686// let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
9687// let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
9688// let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
9689// snapshot.clip_offset_utf16(new_start, Bias::Left)
9690// ..snapshot.clip_offset_utf16(new_end, Bias::Right)
9691// })
9692// .collect::<Vec<_>>();
9693
9694// drop(snapshot);
9695// this.change_selections(None, cx, |selections| {
9696// selections.select_ranges(new_selected_ranges)
9697// });
9698// }
9699// });
9700
9701// self.ime_transaction = self.ime_transaction.or(transaction);
9702// if let Some(transaction) = self.ime_transaction {
9703// self.buffer.update(cx, |buffer, cx| {
9704// buffer.group_until_transaction(transaction, cx);
9705// });
9706// }
9707
9708// if self.text_highlights::<InputComposition>(cx).is_none() {
9709// self.ime_transaction.take();
9710// }
9711// }
9712// }
9713
9714// fn build_style(
9715// settings: &ThemeSettings,
9716// get_field_editor_theme: Option<&GetFieldEditorTheme>,
9717// override_text_style: Option<&OverrideTextStyle>,
9718// cx: &mut AppContext,
9719// ) -> EditorStyle {
9720// let font_cache = cx.font_cache();
9721// let line_height_scalar = settings.line_height();
9722// let theme_id = settings.theme.meta.id;
9723// let mut theme = settings.theme.editor.clone();
9724// let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
9725// let field_editor_theme = get_field_editor_theme(&settings.theme);
9726// theme.text_color = field_editor_theme.text.color;
9727// theme.selection = field_editor_theme.selection;
9728// theme.background = field_editor_theme
9729// .container
9730// .background_color
9731// .unwrap_or_default();
9732// EditorStyle {
9733// text: field_editor_theme.text,
9734// placeholder_text: field_editor_theme.placeholder_text,
9735// line_height_scalar,
9736// theme,
9737// theme_id,
9738// }
9739// } else {
9740// todo!();
9741// // let font_family_id = settings.buffer_font_family;
9742// // let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
9743// // let font_properties = Default::default();
9744// // let font_id = font_cache
9745// // .select_font(font_family_id, &font_properties)
9746// // .unwrap();
9747// // let font_size = settings.buffer_font_size(cx);
9748// // EditorStyle {
9749// // text: TextStyle {
9750// // color: settings.theme.editor.text_color,
9751// // font_family_name,
9752// // font_family_id,
9753// // font_id,
9754// // font_size,
9755// // font_properties,
9756// // underline: Default::default(),
9757// // soft_wrap: false,
9758// // },
9759// // placeholder_text: None,
9760// // line_height_scalar,
9761// // theme,
9762// // theme_id,
9763// // }
9764// };
9765
9766// if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
9767// if let Some(highlighted) = style
9768// .text
9769// .clone()
9770// .highlight(highlight_style, font_cache)
9771// .log_err()
9772// {
9773// style.text = highlighted;
9774// }
9775// }
9776
9777// style
9778// }
9779
9780trait SelectionExt {
9781 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
9782 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
9783 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
9784 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
9785 -> Range<u32>;
9786}
9787
9788impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
9789 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
9790 let start = self.start.to_point(buffer);
9791 let end = self.end.to_point(buffer);
9792 if self.reversed {
9793 end..start
9794 } else {
9795 start..end
9796 }
9797 }
9798
9799 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
9800 let start = self.start.to_offset(buffer);
9801 let end = self.end.to_offset(buffer);
9802 if self.reversed {
9803 end..start
9804 } else {
9805 start..end
9806 }
9807 }
9808
9809 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
9810 let start = self
9811 .start
9812 .to_point(&map.buffer_snapshot)
9813 .to_display_point(map);
9814 let end = self
9815 .end
9816 .to_point(&map.buffer_snapshot)
9817 .to_display_point(map);
9818 if self.reversed {
9819 end..start
9820 } else {
9821 start..end
9822 }
9823 }
9824
9825 fn spanned_rows(
9826 &self,
9827 include_end_if_at_line_start: bool,
9828 map: &DisplaySnapshot,
9829 ) -> Range<u32> {
9830 let start = self.start.to_point(&map.buffer_snapshot);
9831 let mut end = self.end.to_point(&map.buffer_snapshot);
9832 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
9833 end.row -= 1;
9834 }
9835
9836 let buffer_start = map.prev_line_boundary(start).0;
9837 let buffer_end = map.next_line_boundary(end).0;
9838 buffer_start.row..buffer_end.row + 1
9839 }
9840}
9841
9842impl<T: InvalidationRegion> InvalidationStack<T> {
9843 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
9844 where
9845 S: Clone + ToOffset,
9846 {
9847 while let Some(region) = self.last() {
9848 let all_selections_inside_invalidation_ranges =
9849 if selections.len() == region.ranges().len() {
9850 selections
9851 .iter()
9852 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
9853 .all(|(selection, invalidation_range)| {
9854 let head = selection.head().to_offset(buffer);
9855 invalidation_range.start <= head && invalidation_range.end >= head
9856 })
9857 } else {
9858 false
9859 };
9860
9861 if all_selections_inside_invalidation_ranges {
9862 break;
9863 } else {
9864 self.pop();
9865 }
9866 }
9867 }
9868}
9869
9870impl<T> Default for InvalidationStack<T> {
9871 fn default() -> Self {
9872 Self(Default::default())
9873 }
9874}
9875
9876impl<T> Deref for InvalidationStack<T> {
9877 type Target = Vec<T>;
9878
9879 fn deref(&self) -> &Self::Target {
9880 &self.0
9881 }
9882}
9883
9884impl<T> DerefMut for InvalidationStack<T> {
9885 fn deref_mut(&mut self) -> &mut Self::Target {
9886 &mut self.0
9887 }
9888}
9889
9890impl InvalidationRegion for SnippetState {
9891 fn ranges(&self) -> &[Range<Anchor>] {
9892 &self.ranges[self.active_index]
9893 }
9894}
9895
9896// impl Deref for EditorStyle {
9897// type Target = theme::Editor;
9898
9899// fn deref(&self) -> &Self::Target {
9900// &self.theme
9901// }
9902// }
9903
9904pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
9905 let mut highlighted_lines = Vec::new();
9906
9907 for (index, line) in diagnostic.message.lines().enumerate() {
9908 let line = match &diagnostic.source {
9909 Some(source) if index == 0 => {
9910 let source_highlight = Vec::from_iter(0..source.len());
9911 highlight_diagnostic_message(source_highlight, &format!("{source}: {line}"))
9912 }
9913
9914 _ => highlight_diagnostic_message(Vec::new(), line),
9915 };
9916 highlighted_lines.push(line);
9917 }
9918 let message = diagnostic.message;
9919 Arc::new(move |cx: &mut BlockContext| {
9920 todo!()
9921 // let message = message.clone();
9922 // let settings = ThemeSettings::get_global(cx);
9923 // let tooltip_style = settings.theme.tooltip.clone();
9924 // let theme = &settings.theme.editor;
9925 // let style = diagnostic_style(diagnostic.severity, is_valid, theme);
9926 // let font_size = (style.text_scale_factor * settings.buffer_font_size(cx)).round();
9927 // let anchor_x = cx.anchor_x;
9928 // enum BlockContextToolip {}
9929 // MouseEventHandler::new::<BlockContext, _>(cx.block_id, cx, |_, _| {
9930 // Flex::column()
9931 // .with_children(highlighted_lines.iter().map(|(line, highlights)| {
9932 // Label::new(
9933 // line.clone(),
9934 // style.message.clone().with_font_size(font_size),
9935 // )
9936 // .with_highlights(highlights.clone())
9937 // .contained()
9938 // .with_margin_left(anchor_x)
9939 // }))
9940 // .aligned()
9941 // .left()
9942 // .into_any()
9943 // })
9944 // .with_cursor_style(CursorStyle::PointingHand)
9945 // .on_click(MouseButton::Left, move |_, _, cx| {
9946 // cx.write_to_clipboard(ClipboardItem::new(message.clone()));
9947 // })
9948 // // We really need to rethink this ID system...
9949 // .with_tooltip::<BlockContextToolip>(
9950 // cx.block_id,
9951 // "Copy diagnostic message",
9952 // None,
9953 // tooltip_style,
9954 // cx,
9955 // )
9956 // .into_any()
9957 })
9958}
9959
9960pub fn highlight_diagnostic_message(
9961 initial_highlights: Vec<usize>,
9962 message: &str,
9963) -> (String, Vec<usize>) {
9964 let mut message_without_backticks = String::new();
9965 let mut prev_offset = 0;
9966 let mut inside_block = false;
9967 let mut highlights = initial_highlights;
9968 for (match_ix, (offset, _)) in message
9969 .match_indices('`')
9970 .chain([(message.len(), "")])
9971 .enumerate()
9972 {
9973 message_without_backticks.push_str(&message[prev_offset..offset]);
9974 if inside_block {
9975 highlights.extend(prev_offset - match_ix..offset - match_ix);
9976 }
9977
9978 inside_block = !inside_block;
9979 prev_offset = offset + 1;
9980 }
9981
9982 (message_without_backticks, highlights)
9983}
9984
9985pub fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, theme: &ThemeVariant) -> Hsla {
9986 match (severity, valid) {
9987 (DiagnosticSeverity::ERROR, true) => theme.status().error,
9988 (DiagnosticSeverity::ERROR, false) => theme.status().error,
9989 (DiagnosticSeverity::WARNING, true) => theme.status().warning,
9990 (DiagnosticSeverity::WARNING, false) => theme.status().warning,
9991 (DiagnosticSeverity::INFORMATION, true) => theme.status().info,
9992 (DiagnosticSeverity::INFORMATION, false) => theme.status().info,
9993 (DiagnosticSeverity::HINT, true) => theme.status().info,
9994 (DiagnosticSeverity::HINT, false) => theme.status().info,
9995 _ => theme.status().ignored,
9996 }
9997}
9998
9999// pub fn combine_syntax_and_fuzzy_match_highlights(
10000// text: &str,
10001// default_style: HighlightStyle,
10002// syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
10003// match_indices: &[usize],
10004// ) -> Vec<(Range<usize>, HighlightStyle)> {
10005// let mut result = Vec::new();
10006// let mut match_indices = match_indices.iter().copied().peekable();
10007
10008// for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
10009// {
10010// syntax_highlight.weight = None;
10011
10012// // Add highlights for any fuzzy match characters before the next
10013// // syntax highlight range.
10014// while let Some(&match_index) = match_indices.peek() {
10015// if match_index >= range.start {
10016// break;
10017// }
10018// match_indices.next();
10019// let end_index = char_ix_after(match_index, text);
10020// let mut match_style = default_style;
10021// match_style.weight = Some(FontWeight::BOLD);
10022// result.push((match_index..end_index, match_style));
10023// }
10024
10025// if range.start == usize::MAX {
10026// break;
10027// }
10028
10029// // Add highlights for any fuzzy match characters within the
10030// // syntax highlight range.
10031// let mut offset = range.start;
10032// while let Some(&match_index) = match_indices.peek() {
10033// if match_index >= range.end {
10034// break;
10035// }
10036
10037// match_indices.next();
10038// if match_index > offset {
10039// result.push((offset..match_index, syntax_highlight));
10040// }
10041
10042// let mut end_index = char_ix_after(match_index, text);
10043// while let Some(&next_match_index) = match_indices.peek() {
10044// if next_match_index == end_index && next_match_index < range.end {
10045// end_index = char_ix_after(next_match_index, text);
10046// match_indices.next();
10047// } else {
10048// break;
10049// }
10050// }
10051
10052// let mut match_style = syntax_highlight;
10053// match_style.weight = Some(FontWeight::BOLD);
10054// result.push((match_index..end_index, match_style));
10055// offset = end_index;
10056// }
10057
10058// if offset < range.end {
10059// result.push((offset..range.end, syntax_highlight));
10060// }
10061// }
10062
10063// fn char_ix_after(ix: usize, text: &str) -> usize {
10064// ix + text[ix..].chars().next().unwrap().len_utf8()
10065// }
10066
10067// result
10068// }
10069
10070// pub fn styled_runs_for_code_label<'a>(
10071// label: &'a CodeLabel,
10072// syntax_theme: &'a theme::SyntaxTheme,
10073// ) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10074// let fade_out = HighlightStyle {
10075// fade_out: Some(0.35),
10076// ..Default::default()
10077// };
10078
10079// let mut prev_end = label.filter_range.end;
10080// label
10081// .runs
10082// .iter()
10083// .enumerate()
10084// .flat_map(move |(ix, (range, highlight_id))| {
10085// let style = if let Some(style) = highlight_id.style(syntax_theme) {
10086// style
10087// } else {
10088// return Default::default();
10089// };
10090// let mut muted_style = style;
10091// muted_style.highlight(fade_out);
10092
10093// let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10094// if range.start >= label.filter_range.end {
10095// if range.start > prev_end {
10096// runs.push((prev_end..range.start, fade_out));
10097// }
10098// runs.push((range.clone(), muted_style));
10099// } else if range.end <= label.filter_range.end {
10100// runs.push((range.clone(), style));
10101// } else {
10102// runs.push((range.start..label.filter_range.end, style));
10103// runs.push((label.filter_range.end..range.end, muted_style));
10104// }
10105// prev_end = cmp::max(prev_end, range.end);
10106
10107// if ix + 1 == label.runs.len() && label.text.len() > prev_end {
10108// runs.push((prev_end..label.text.len(), fade_out));
10109// }
10110
10111// runs
10112// })
10113
10114pub fn split_words<'a>(text: &'a str) -> impl std::iter::Iterator<Item = &'a str> + 'a {
10115 let mut index = 0;
10116 let mut codepoints = text.char_indices().peekable();
10117
10118 std::iter::from_fn(move || {
10119 let start_index = index;
10120 while let Some((new_index, codepoint)) = codepoints.next() {
10121 index = new_index + codepoint.len_utf8();
10122 let current_upper = codepoint.is_uppercase();
10123 let next_upper = codepoints
10124 .peek()
10125 .map(|(_, c)| c.is_uppercase())
10126 .unwrap_or(false);
10127
10128 if !current_upper && next_upper {
10129 return Some(&text[start_index..index]);
10130 }
10131 }
10132
10133 index = text.len();
10134 if start_index < text.len() {
10135 return Some(&text[start_index..]);
10136 }
10137 None
10138 })
10139 .flat_map(|word| word.split_inclusive('_'))
10140 .flat_map(|word| word.split_inclusive('-'))
10141}
10142
10143trait RangeToAnchorExt {
10144 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10145}
10146
10147impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10148 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10149 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10150 }
10151}