Kirill BulatovPort to gpui155374e82 years agoHistory
10122 lines · 369.5 KB · Rust
RawDownload
mod blink_manager;pub mod display_map;mod editor_settings;mod element;mod inlay_hint_cache; mod git;mod highlight_matching_bracket;mod hover_popover;pub mod items;mod link_go_to_definition;mod mouse_context_menu;pub mod movement;mod persistence;mod rust_analyzer_ext;pub mod scroll;pub mod selections_collection; #[cfg(test)]mod editor_tests;#[cfg(any(test, feature = "test-support"))]pub mod test; use ::git::diff::DiffHunk;use aho_corasick::AhoCorasick;use anyhow::{anyhow, Context, Result};use blink_manager::BlinkManager;use client::{Client, Collaborator, ParticipantIndex, TelemetrySettings};use clock::{Global, ReplicaId};use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};use convert_case::{Case, Casing};use copilot::Copilot;pub use display_map::DisplayPoint;use display_map::*;pub use editor_settings::EditorSettings;pub use element::{    Cursor, EditorElement, HighlightedRange, HighlightedRangeLine, LineWithInvisibles,};use futures::FutureExt;use fuzzy::{StringMatch, StringMatchCandidate};use gpui::{    actions,    color::Color,    elements::*,    executor,    fonts::{self, HighlightStyle, TextStyle},    geometry::vector::{vec2f, Vector2F},    impl_actions,    keymap_matcher::KeymapContext,    platform::{CursorStyle, MouseButton},    serde_json, AnyElement, AnyViewHandle, AppContext, AsyncAppContext, ClipboardItem,    CursorRegion, Element, Entity, ModelHandle, MouseRegion, Subscription, Task, View, ViewContext,    ViewHandle, WeakViewHandle, WindowContext,};use highlight_matching_bracket::refresh_matching_bracket_highlights;use hover_popover::{hide_hover, HoverState};use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};pub use items::MAX_TAB_TITLE_LEN;use itertools::Itertools;pub use language::{char_kind, CharKind};use language::{    language_settings::{self, all_language_settings, InlayHintSettings},    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, CodeAction, CodeLabel,    Completion, CursorShape, Diagnostic, DiagnosticSeverity, Documentation, File, IndentKind,    IndentSize, Language, LanguageRegistry, LanguageServerName, OffsetRangeExt, OffsetUtf16, Point,    Selection, SelectionGoal, TransactionId,};use link_go_to_definition::{    hide_link_definition, show_link_definition, GoToDefinitionLink, InlayHighlight,    LinkGoToDefinitionState,};use log::error;use lsp::LanguageServerId;use movement::TextLayoutDetails;use multi_buffer::ToOffsetUtf16;pub use multi_buffer::{    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,    ToPoint,};use ordered_float::OrderedFloat;use parking_lot::RwLock;use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};use rand::{seq::SliceRandom, thread_rng};use rpc::proto::{self, PeerId};use scroll::{    autoscroll::Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide,};use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};use serde::{Deserialize, Serialize};use settings::SettingsStore;use smallvec::SmallVec;use snippet::Snippet;use std::{    any::TypeId,    borrow::Cow,    cmp::{self, Ordering, Reverse},    mem,    num::NonZeroU32,    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},    path::Path,    sync::Arc,    time::{Duration, Instant},};pub use sum_tree::Bias;use sum_tree::TreeMap;use text::Rope;use theme::{DiagnosticStyle, Theme, ThemeSettings};use util::{post_inc, RangeExt, ResultExt, TryFutureExt};use workspace::{ItemNavHistory, SplitDirection, ViewId, Workspace}; use crate::git::diff_hunk_to_display; const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);const MAX_LINE_LEN: usize = 1024;const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;const MAX_SELECTION_HISTORY_LEN: usize = 1024;const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75); pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2); pub fn render_parsed_markdown<Tag: 'static>(    parsed: &language::ParsedMarkdown,    editor_style: &EditorStyle,    workspace: Option<WeakViewHandle<Workspace>>,    cx: &mut ViewContext<Editor>,) -> Text {    enum RenderedMarkdown {}     let parsed = parsed.clone();    let view_id = cx.view_id();    let code_span_background_color = editor_style.document_highlight_read_background;     let mut region_id = 0;     Text::new(parsed.text, editor_style.text.clone())        .with_highlights(            parsed                .highlights                .iter()                .filter_map(|(range, highlight)| {                    let highlight = highlight.to_highlight_style(&editor_style.syntax)?;                    Some((range.clone(), highlight))                })                .collect::<Vec<_>>(),        )        .with_custom_runs(parsed.region_ranges, move |ix, bounds, cx| {            region_id += 1;            let region = parsed.regions[ix].clone();             if let Some(link) = region.link {                cx.scene().push_cursor_region(CursorRegion {                    bounds,                    style: CursorStyle::PointingHand,                });                cx.scene().push_mouse_region(                    MouseRegion::new::<(RenderedMarkdown, Tag)>(view_id, region_id, bounds)                        .on_down::<Editor, _>(MouseButton::Left, move |_, _, cx| match &link {                            markdown::Link::Web { url } => cx.platform().open_url(url),                            markdown::Link::Path { path } => {                                if let Some(workspace) = &workspace {                                    _ = workspace.update(cx, |workspace, cx| {                                        workspace.open_abs_path(path.clone(), false, cx).detach();                                    });                                }                            }                        }),                );            }             if region.code {                cx.scene().push_quad(gpui::Quad {                    bounds,                    background: Some(code_span_background_color),                    border: Default::default(),                    corner_radii: (2.0).into(),                });            }        })        .with_soft_wrap(true)} #[derive(Clone, Deserialize, PartialEq, Default)]pub struct SelectNext {    #[serde(default)]    pub replace_newest: bool,} #[derive(Clone, Deserialize, PartialEq, Default)]pub struct SelectPrevious {    #[serde(default)]    pub replace_newest: bool,} #[derive(Clone, Deserialize, PartialEq, Default)]pub struct SelectAllMatches {    #[serde(default)]    pub replace_newest: bool,} #[derive(Clone, Deserialize, PartialEq)]pub struct SelectToBeginningOfLine {    #[serde(default)]    stop_at_soft_wraps: bool,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct MovePageUp {    #[serde(default)]    center_cursor: bool,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct MovePageDown {    #[serde(default)]    center_cursor: bool,} #[derive(Clone, Deserialize, PartialEq)]pub struct SelectToEndOfLine {    #[serde(default)]    stop_at_soft_wraps: bool,} #[derive(Clone, Deserialize, PartialEq)]pub struct ToggleCodeActions {    #[serde(default)]    pub deployed_from_indicator: bool,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct ConfirmCompletion {    #[serde(default)]    pub item_ix: Option<usize>,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct ConfirmCodeAction {    #[serde(default)]    pub item_ix: Option<usize>,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct ToggleComments {    #[serde(default)]    pub advance_downwards: bool,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct FoldAt {    pub buffer_row: u32,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct UnfoldAt {    pub buffer_row: u32,} #[derive(Clone, Default, Deserialize, PartialEq)]pub struct GutterHover {    pub hovered: bool,} #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]pub enum InlayId {    Suggestion(usize),    Hint(usize),} impl InlayId {    fn id(&self) -> usize {        match self {            Self::Suggestion(id) => *id,            Self::Hint(id) => *id,        }    }} actions!(    editor,    [        Cancel,        Backspace,        Delete,        Newline,        NewlineAbove,        NewlineBelow,        GoToDiagnostic,        GoToPrevDiagnostic,        GoToHunk,        GoToPrevHunk,        Indent,        Outdent,        DeleteLine,        DeleteToPreviousWordStart,        DeleteToPreviousSubwordStart,        DeleteToNextWordEnd,        DeleteToNextSubwordEnd,        DeleteToBeginningOfLine,        DeleteToEndOfLine,        CutToEndOfLine,        DuplicateLine,        ExpandMacroRecursively,        MoveLineUp,        MoveLineDown,        JoinLines,        SortLinesCaseSensitive,        SortLinesCaseInsensitive,        ReverseLines,        ShuffleLines,        ConvertToUpperCase,        ConvertToLowerCase,        ConvertToTitleCase,        ConvertToSnakeCase,        ConvertToKebabCase,        ConvertToUpperCamelCase,        ConvertToLowerCamelCase,        Transpose,        Cut,        Copy,        Paste,        Undo,        Redo,        MoveUp,        PageUp,        MoveDown,        PageDown,        MoveLeft,        MoveRight,        MoveToPreviousWordStart,        MoveToPreviousSubwordStart,        MoveToNextWordEnd,        MoveToNextSubwordEnd,        MoveToBeginningOfLine,        MoveToEndOfLine,        MoveToStartOfParagraph,        MoveToEndOfParagraph,        MoveToBeginning,        MoveToEnd,        SelectUp,        SelectDown,        SelectLeft,        SelectRight,        SelectToPreviousWordStart,        SelectToPreviousSubwordStart,        SelectToNextWordEnd,        SelectToNextSubwordEnd,        SelectToStartOfParagraph,        SelectToEndOfParagraph,        SelectToBeginning,        SelectToEnd,        SelectAll,        SelectLine,        SplitSelectionIntoLines,        AddSelectionAbove,        AddSelectionBelow,        Tab,        TabPrev,        ShowCharacterPalette,        SelectLargerSyntaxNode,        SelectSmallerSyntaxNode,        GoToDefinition,        GoToDefinitionSplit,        GoToTypeDefinition,        GoToTypeDefinitionSplit,        MoveToEnclosingBracket,        UndoSelection,        RedoSelection,        FindAllReferences,        Rename,        ConfirmRename,        Fold,        UnfoldLines,        FoldSelectedRanges,        ShowCompletions,        OpenExcerpts,        RestartLanguageServer,        Hover,        Format,        ToggleSoftWrap,        ToggleInlayHints,        RevealInFinder,        CopyPath,        CopyRelativePath,        CopyHighlightJson,        ContextMenuFirst,        ContextMenuPrev,        ContextMenuNext,        ContextMenuLast,    ]); impl_actions!(    editor,    [        SelectNext,        SelectPrevious,        SelectAllMatches,        SelectToBeginningOfLine,        SelectToEndOfLine,        ToggleCodeActions,        MovePageUp,        MovePageDown,        ConfirmCompletion,        ConfirmCodeAction,        ToggleComments,        FoldAt,        UnfoldAt,        GutterHover    ]); enum DocumentHighlightRead {}enum DocumentHighlightWrite {}enum InputComposition {} #[derive(Copy, Clone, PartialEq, Eq)]pub enum Direction {    Prev,    Next,} pub fn init_settings(cx: &mut AppContext) {    settings::register::<EditorSettings>(cx);} pub fn init(cx: &mut AppContext) {    init_settings(cx);     rust_analyzer_ext::apply_related_actions(cx);    cx.add_action(Editor::new_file);    cx.add_action(Editor::new_file_in_direction);    cx.add_action(Editor::cancel);    cx.add_action(Editor::newline);    cx.add_action(Editor::newline_above);    cx.add_action(Editor::newline_below);    cx.add_action(Editor::backspace);    cx.add_action(Editor::delete);    cx.add_action(Editor::tab);    cx.add_action(Editor::tab_prev);    cx.add_action(Editor::indent);    cx.add_action(Editor::outdent);    cx.add_action(Editor::delete_line);    cx.add_action(Editor::join_lines);    cx.add_action(Editor::sort_lines_case_sensitive);    cx.add_action(Editor::sort_lines_case_insensitive);    cx.add_action(Editor::reverse_lines);    cx.add_action(Editor::shuffle_lines);    cx.add_action(Editor::convert_to_upper_case);    cx.add_action(Editor::convert_to_lower_case);    cx.add_action(Editor::convert_to_title_case);    cx.add_action(Editor::convert_to_snake_case);    cx.add_action(Editor::convert_to_kebab_case);    cx.add_action(Editor::convert_to_upper_camel_case);    cx.add_action(Editor::convert_to_lower_camel_case);    cx.add_action(Editor::delete_to_previous_word_start);    cx.add_action(Editor::delete_to_previous_subword_start);    cx.add_action(Editor::delete_to_next_word_end);    cx.add_action(Editor::delete_to_next_subword_end);    cx.add_action(Editor::delete_to_beginning_of_line);    cx.add_action(Editor::delete_to_end_of_line);    cx.add_action(Editor::cut_to_end_of_line);    cx.add_action(Editor::duplicate_line);    cx.add_action(Editor::move_line_up);    cx.add_action(Editor::move_line_down);    cx.add_action(Editor::transpose);    cx.add_action(Editor::cut);    cx.add_action(Editor::copy);    cx.add_action(Editor::paste);    cx.add_action(Editor::undo);    cx.add_action(Editor::redo);    cx.add_action(Editor::move_up);    cx.add_action(Editor::move_page_up);    cx.add_action(Editor::move_down);    cx.add_action(Editor::move_page_down);    cx.add_action(Editor::next_screen);    cx.add_action(Editor::move_left);    cx.add_action(Editor::move_right);    cx.add_action(Editor::move_to_previous_word_start);    cx.add_action(Editor::move_to_previous_subword_start);    cx.add_action(Editor::move_to_next_word_end);    cx.add_action(Editor::move_to_next_subword_end);    cx.add_action(Editor::move_to_beginning_of_line);    cx.add_action(Editor::move_to_end_of_line);    cx.add_action(Editor::move_to_start_of_paragraph);    cx.add_action(Editor::move_to_end_of_paragraph);    cx.add_action(Editor::move_to_beginning);    cx.add_action(Editor::move_to_end);    cx.add_action(Editor::select_up);    cx.add_action(Editor::select_down);    cx.add_action(Editor::select_left);    cx.add_action(Editor::select_right);    cx.add_action(Editor::select_to_previous_word_start);    cx.add_action(Editor::select_to_previous_subword_start);    cx.add_action(Editor::select_to_next_word_end);    cx.add_action(Editor::select_to_next_subword_end);    cx.add_action(Editor::select_to_beginning_of_line);    cx.add_action(Editor::select_to_end_of_line);    cx.add_action(Editor::select_to_start_of_paragraph);

Lines 1–500 of 10122.