9908 lines · 361.2 KB · Rust
RawDownload
#![allow(unused)]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 as _, Result};use blink_manager::BlinkManager;use client::{Client, Collaborator, ParticipantIndex, TelemetrySettings};use clock::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 git::diff_hunk_to_display;use gpui::{    actions, div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,    AnyElement, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,    DispatchPhase, Div, ElementId, EventEmitter, FocusHandle, FocusableView, FontFeatures,    FontStyle, FontWeight, HighlightStyle, Hsla, InputHandler, InteractiveText, KeyContext, Model,    MouseButton, ParentElement, Pixels, Render, RenderOnce, SharedString, Styled, StyledText,    Subscription, Task, TextRun, TextStyle, UniformListScrollHandle, View, ViewContext,    VisualContext, WeakView, WhiteSpace, 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, Documentation, IndentKind, IndentSize, Language,    LanguageRegistry, LanguageServerName, OffsetRangeExt, Point, Selection, SelectionGoal,    TransactionId,};use lazy_static::lazy_static;use link_go_to_definition::{GoToDefinitionLink, InlayHighlight, LinkGoToDefinitionState};use lsp::{DiagnosticSeverity, LanguageServerId};use mouse_context_menu::MouseContextMenu;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::{Mutex, RwLock};use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};use rand::prelude::*;use rpc::proto::{self, *};use scroll::{    autoscroll::Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide,};use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};use serde::{Deserialize, Serialize};use settings::{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,    sync::Weak,    time::{Duration, Instant},};pub use sum_tree::Bias;use sum_tree::TreeMap;use text::{OffsetUtf16, Rope};use theme::{    ActiveTheme, DiagnosticStyle, PlayerColor, SyntaxTheme, Theme, ThemeColors, ThemeSettings,};use ui::{    h_stack, v_stack, ButtonSize, ButtonStyle, HighlightedLabel, Icon, IconButton, Popover, Tooltip,};use ui::{prelude::*, IconSize};use util::{post_inc, RangeExt, ResultExt, TryFutureExt};use workspace::{    item::{Item, ItemEvent, ItemHandle},    searchable::SearchEvent,    ItemNavHistory, Pane, SplitDirection, ViewId, Workspace,}; 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(    element_id: impl Into<ElementId>,    parsed: &language::ParsedMarkdown,    editor_style: &EditorStyle,    workspace: Option<WeakView<Workspace>>,    cx: &mut ViewContext<Editor>,) -> InteractiveText {    let code_span_background_color = cx        .theme()        .colors()        .editor_document_highlight_read_background;     let highlights = gpui::combine_highlights(        parsed.highlights.iter().filter_map(|(range, highlight)| {            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;            Some((range.clone(), highlight))        }),        parsed            .regions            .iter()            .zip(&parsed.region_ranges)            .filter_map(|(region, range)| {                if region.code {                    Some((                        range.clone(),                        HighlightStyle {                            background_color: Some(code_span_background_color),                            ..Default::default()                        },                    ))                } else {                    None                }            }),    );     let mut links = Vec::new();    let mut link_ranges = Vec::new();    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {        if let Some(link) = region.link.clone() {            links.push(link);            link_ranges.push(range.clone());        }    }     InteractiveText::new(        element_id,        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),    )    .on_click(link_ranges, move |clicked_range_ix, cx| {        match &links[clicked_range_ix] {            markdown::Link::Web { url } => cx.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();                    });                }            }        }    })} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct SelectNext {    #[serde(default)]    pub replace_newest: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct SelectPrevious {    #[serde(default)]    pub replace_newest: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct SelectAllMatches {    #[serde(default)]    pub replace_newest: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct SelectToBeginningOfLine {    #[serde(default)]    stop_at_soft_wraps: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct MovePageUp {    #[serde(default)]    center_cursor: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct MovePageDown {    #[serde(default)]    center_cursor: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct SelectToEndOfLine {    #[serde(default)]    stop_at_soft_wraps: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct ToggleCodeActions {    #[serde(default)]    pub deployed_from_indicator: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct ConfirmCompletion {    #[serde(default)]    pub item_ix: Option<usize>,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct ConfirmCodeAction {    #[serde(default)]    pub item_ix: Option<usize>,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct ToggleComments {    #[serde(default)]    pub advance_downwards: bool,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct FoldAt {    pub buffer_row: u32,} #[derive(PartialEq, Clone, Deserialize, Default)]pub struct UnfoldAt {    pub buffer_row: u32,} impl_actions!(    editor,    [        SelectNext,        SelectPrevious,        SelectAllMatches,        SelectToBeginningOfLine,        MovePageUp,        MovePageDown,        SelectToEndOfLine,        ToggleCodeActions,        ConfirmCompletion,        ConfirmCodeAction,        ToggleComments,        FoldAt,        UnfoldAt    ]); #[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,    [        AddSelectionAbove,        AddSelectionBelow,        Backspace,        Cancel,        ConfirmRename,        ContextMenuFirst,        ContextMenuLast,        ContextMenuNext,        ContextMenuPrev,        ConvertToKebabCase,        ConvertToLowerCamelCase,        ConvertToLowerCase,        ConvertToSnakeCase,        ConvertToTitleCase,        ConvertToUpperCamelCase,        ConvertToUpperCase,        Copy,        CopyHighlightJson,        CopyPath,        CopyRelativePath,        Cut,        CutToEndOfLine,        Delete,        DeleteLine,        DeleteToBeginningOfLine,        DeleteToEndOfLine,        DeleteToNextSubwordEnd,        DeleteToNextWordEnd,        DeleteToPreviousSubwordStart,        DeleteToPreviousWordStart,        DuplicateLine,        ExpandMacroRecursively,        FindAllReferences,        Fold,        FoldSelectedRanges,        Format,        GoToDefinition,        GoToDefinitionSplit,        GoToDiagnostic,        GoToHunk,        GoToPrevDiagnostic,        GoToPrevHunk,        GoToTypeDefinition,        GoToTypeDefinitionSplit,        HalfPageDown,        HalfPageUp,        Hover,        Indent,        JoinLines,        LineDown,        LineUp,        MoveDown,        MoveLeft,        MoveLineDown,        MoveLineUp,        MoveRight,        MoveToBeginning,        MoveToBeginningOfLine,        MoveToEnclosingBracket,        MoveToEnd,        MoveToEndOfLine,        MoveToEndOfParagraph,        MoveToNextSubwordEnd,        MoveToNextWordEnd,        MoveToPreviousSubwordStart,        MoveToPreviousWordStart,        MoveToStartOfParagraph,        MoveUp,        Newline,        NewlineAbove,        NewlineBelow,        NextScreen,        OpenExcerpts,        Outdent,        PageDown,        PageUp,        Paste,        Redo,        RedoSelection,        Rename,        RestartLanguageServer,        RevealInFinder,        ReverseLines,        ScrollCursorBottom,        ScrollCursorCenter,        ScrollCursorTop,        SelectAll,        SelectDown,        SelectLargerSyntaxNode,        SelectLeft,        SelectLine,        SelectRight,        SelectSmallerSyntaxNode,        SelectToBeginning,        SelectToEnd,        SelectToEndOfParagraph,        SelectToNextSubwordEnd,        SelectToNextWordEnd,        SelectToPreviousSubwordStart,        SelectToPreviousWordStart,        SelectToStartOfParagraph,        SelectUp,        ShowCharacterPalette,        ShowCompletions,        ShuffleLines,        SortLinesCaseInsensitive,        SortLinesCaseSensitive,        SplitSelectionIntoLines,        Tab,        TabPrev,        ToggleInlayHints,        ToggleSoftWrap,        Transpose,        Undo,        UndoSelection,        UnfoldLines,    ]); enum DocumentHighlightRead {}enum DocumentHighlightWrite {}enum InputComposition {} #[derive(Copy, Clone, PartialEq, Eq)]pub enum Direction {    Prev,    Next,} pub fn init_settings(cx: &mut AppContext) {    EditorSettings::register(cx);} pub fn init(cx: &mut AppContext) {    init_settings(cx);     workspace::register_project_item::<Editor>(cx);    workspace::register_followable_item::<Editor>(cx);    workspace::register_deserializable_item::<Editor>(cx);    cx.observe_new_views(        |workspace: &mut Workspace, cx: &mut ViewContext<Workspace>| {            workspace.register_action(Editor::new_file);            workspace.register_action(Editor::new_file_in_direction);        },    )    .detach();     cx.on_action(move |_: &workspace::NewFile, cx| {        let app_state = cx.global::<Weak<workspace::AppState>>();        if let Some(app_state) = app_state.upgrade() {            workspace::open_new(&app_state, cx, |workspace, cx| {                Editor::new_file(workspace, &Default::default(), cx)            })            .detach();        }    });    cx.on_action(move |_: &workspace::NewWindow, cx| {        let app_state = cx.global::<Weak<workspace::AppState>>();        if let Some(app_state) = app_state.upgrade() {            workspace::open_new(&app_state, cx, |workspace, cx| {                Editor::new_file(workspace, &Default::default(), cx)            })            .detach();        }    });} trait InvalidationRegion {    fn ranges(&self) -> &[Range<Anchor>];} #[derive(Clone, Debug, PartialEq)]pub enum SelectPhase {    Begin {        position: DisplayPoint,        add: bool,        click_count: usize,    },    BeginColumnar {        position: DisplayPoint,        goal_column: u32,    },    Extend {        position: DisplayPoint,        click_count: usize,    },    Update {        position: DisplayPoint,        goal_column: u32,        scroll_position: gpui::Point<f32>,    },    End,} #[derive(Clone, Debug)]pub enum SelectMode {    Character,    Word(Range<Anchor>),    Line(Range<Anchor>),

Lines 1–500 of 9908.