Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Render control characters in tab titles and project panel entries (#62875)
Enzo GAZZOLIe3056061d44c
diff --git a/crates/editor/src/items.rs b/crates/editor/src/items.rsindex 2e82e514ff8..f451b3968cb 100644--- a/crates/editor/src/items.rs+++ b/crates/editor/src/items.rs@@ -811,6 +811,7 @@ impl Item for Editor {params.max_title_len.unwrap_or(MAX_TAB_TITLE_LEN),)})+ .single_line().color(label_color).when(params.truncate_title_middle, |this| {this.truncate_middle().flex_1()@@ -821,6 +822,7 @@ impl Item for Editor {.when_some(description, |this, description| {this.child(Label::new(description)+ .single_line().size(LabelSize::XSmall).when(params.truncate_title_middle, |this| {this.truncate_start().flex_shrink()diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rsindex ff3158f22c6..77b6a3fb591 100644--- a/crates/file_finder/src/file_finder.rs+++ b/crates/file_finder/src/file_finder.rs@@ -1416,8 +1416,9 @@ impl FileFinderDelegate {}(- HighlightedLabel::new(file_name, file_name_positions),+ HighlightedLabel::new(file_name, file_name_positions).single_line(),HighlightedLabel::new(full_path, full_path_positions)+ .single_line().size(LabelSize::Small).color(Color::Muted),)diff --git a/crates/git_ui/src/branch_diff.rs b/crates/git_ui/src/branch_diff.rsindex 685acea448c..d4684ba981c 100644--- a/crates/git_ui/src/branch_diff.rs+++ b/crates/git_ui/src/branch_diff.rs@@ -14,7 +14,7 @@ use editor::{};use git::{repository::DiffType, status::FileStatus};use gpui::{- Action, AnyElement, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable, Render,+ Action, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable, Render,SharedString, Subscription, Task, WeakEntity,};use language::{BufferId, Capability};@@ -34,7 +34,7 @@ use ui::{DiffStat, Divider, PopoverMenu, Tooltip, prelude::*};use workspace::{ItemHandle, ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation,ToolbarItemView, Workspace,- item::{Item, ItemEvent, SaveOptions, TabContentParams},+ item::{Item, ItemEvent, SaveOptions},notifications::NotifyTaskExt,searchable::SearchableItemHandle,};@@ -475,16 +475,6 @@ impl Item for BranchDiff {Some(self.tab_content_text(0, cx))}- fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {- Label::new(self.tab_content_text(0, cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {match self.diff_base(cx) {DiffBase::Merge { base_ref } => format!("Changes since {}", base_ref).into(),diff --git a/crates/git_ui/src/commit_view.rs b/crates/git_ui/src/commit_view.rsindex 7d720e2f7e2..9a2a0fc0fab 100644--- a/crates/git_ui/src/commit_view.rs+++ b/crates/git_ui/src/commit_view.rs@@ -41,10 +41,7 @@ use util::{ResultExt, paths::PathStyle, rel_path::RelPath, truncate_and_trailoffuse workspace::item::TabTooltipContent;use workspace::{Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,- Workspace,- item::{ItemEvent, TabContentParams},- notifications::NotifyTaskExt,- pane::SaveIntent,+ Workspace, item::ItemEvent, notifications::NotifyTaskExt, pane::SaveIntent,searchable::SearchableItemHandle,};@@ -1059,16 +1056,6 @@ impl Item for CommitView {Some(Icon::new(IconName::GitCommit).color(Color::Muted))}- fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {- Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {let short_sha = self.commit.sha.get(0..7).unwrap_or(&*self.commit.sha);let subject = truncate_and_trailoff(self.commit.message.split('\n').next().unwrap(), 20);diff --git a/crates/git_ui/src/multi_diff_view.rs b/crates/git_ui/src/multi_diff_view.rsindex 46e4b2b6372..15602ac11cf 100644--- a/crates/git_ui/src/multi_diff_view.rs+++ b/crates/git_ui/src/multi_diff_view.rs@@ -6,8 +6,8 @@ use editor::{};use git_ui_core::file_diff_view::build_buffer_diff;use gpui::{- AnyElement, App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle,- Focusable, Font, IntoElement, Render, SharedString, Task, Window,+ App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle, Focusable, Font,+ IntoElement, Render, SharedString, Task, Window,};use language::{Buffer, Capability, HighlightedText, OffsetRangeExt};use multi_buffer::PathKey;@@ -17,12 +17,12 @@ use std::{path::{Path, PathBuf},sync::Arc,};-use ui::{Color, Icon, IconName, Label, LabelCommon as _};+use ui::{Color, Icon, IconName};use util::paths::PathStyle;use util::rel_path::RelPath;use workspace::{Item, ItemHandle as _, ItemNavHistory, ToolbarItemLocation, Workspace,- item::{ItemEvent, SaveOptions, TabContentParams},+ item::{ItemEvent, SaveOptions},searchable::SearchableItemHandle,};@@ -233,16 +233,6 @@ impl Item for MultiDiffView {Some(Icon::new(IconName::Diff).color(Color::Muted))}- fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {- Label::new(self.title())- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_tooltip_text(&self, _cx: &App) -> Option<ui::SharedString> {Some(self.title())}diff --git a/crates/git_ui/src/project_diff.rs b/crates/git_ui/src/project_diff.rsindex 4fa62a513da..f300fe7ca7d 100644--- a/crates/git_ui/src/project_diff.rs+++ b/crates/git_ui/src/project_diff.rs@@ -13,7 +13,7 @@ use editor::{};use git::{Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll, UnstageAndNext};use gpui::{- Action, AnyElement, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable, Render,+ Action, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable, Render,Subscription, Task, WeakEntity, actions,};use language::Capability;@@ -34,7 +34,7 @@ use ui::{DiffStat, Divider, Tooltip, prelude::*};use workspace::{ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,Workspace,- item::{Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},+ item::{Item, ItemEvent, ItemHandle, SaveOptions},searchable::SearchableItemHandle,};use zed_actions::git as git_actions;@@ -423,16 +423,6 @@ impl Item for ProjectDiff {Some(self.tab_content_text(0, cx))}- fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {- Label::new(self.tab_content_text(0, cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {"Uncommitted Changes".into()}diff --git a/crates/git_ui/src/solo_diff_view.rs b/crates/git_ui/src/solo_diff_view.rsindex 904ef069369..bc54d6e4ac0 100644--- a/crates/git_ui/src/solo_diff_view.rs+++ b/crates/git_ui/src/solo_diff_view.rs@@ -12,8 +12,8 @@ use git::{repository::RepoPath, status::StageStatus,};use gpui::{- Action, AnyElement, App, AppContext as _, Context, Empty, Entity, EventEmitter, FocusHandle,- Focusable, HighlightStyle, IntoElement, Render, Subscription, Task, WeakEntity, Window,+ Action, App, AppContext as _, Context, Empty, Entity, EventEmitter, FocusHandle, Focusable,+ HighlightStyle, IntoElement, Render, Subscription, Task, WeakEntity, Window,};use language::{Anchor, Buffer, HighlightedText, OffsetRangeExt as _, Point};use multi_buffer::{MultiBuffer, PathKey, excerpt_context_lines};@@ -32,7 +32,7 @@ use util::paths::{PathExt as _, PathStyle};use workspace::{Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,Workspace,- item::{ItemEvent, SaveOptions, TabContentParams},+ item::{ItemEvent, SaveOptions},notifications::NotifyTaskExt,searchable::SearchableItemHandle,};@@ -377,16 +377,6 @@ impl Item for SoloDiffView {Some(Icon::new(IconName::Diff).color(Color::Muted))}- fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {- Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {self.buffer.read(cx)diff --git a/crates/git_ui/src/staged_diff.rs b/crates/git_ui/src/staged_diff.rsindex 60cd0942a6c..d337dab979f 100644--- a/crates/git_ui/src/staged_diff.rs+++ b/crates/git_ui/src/staged_diff.rs@@ -30,7 +30,7 @@ use util::ResultExt as _;use workspace::{ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,Workspace,- item::{Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},+ item::{Item, ItemEvent, ItemHandle, SaveOptions},searchable::SearchableItemHandle,};@@ -348,16 +348,6 @@ impl Item for StagedDiff {Some("Staged Changes".into())}- fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {- Label::new(self.tab_content_text(0, _cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {"Staged Changes".into()}diff --git a/crates/git_ui/src/text_diff_view.rs b/crates/git_ui/src/text_diff_view.rsindex 5cb3360ba93..97bf88edd8e 100644--- a/crates/git_ui/src/text_diff_view.rs+++ b/crates/git_ui/src/text_diff_view.rs@@ -8,8 +8,8 @@ use editor::{};use futures::{FutureExt, select_biased};use gpui::{- AnyElement, App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle,- Focusable, IntoElement, Render, Task, Window,+ App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle, Focusable,+ IntoElement, Render, Task, Window,};use language::{self, Buffer, Capability, OffsetRangeExt, Point};use project::{Project, ProjectPath};@@ -22,12 +22,12 @@ use std::{sync::Arc,time::Duration,};-use ui::{Color, Icon, IconName, Label, LabelCommon as _, SharedString};+use ui::{Color, Icon, IconName, SharedString};use util::paths::PathExt;use workspace::{Item, ItemNavHistory, Workspace,- item::{ItemEvent, SaveOptions, TabContentParams},+ item::{ItemEvent, SaveOptions},searchable::SearchableItemHandle,};@@ -318,16 +318,6 @@ impl Item for TextDiffView {Some(Icon::new(IconName::Diff).color(Color::Muted))}- fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {- Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {self.title.clone()}diff --git a/crates/git_ui/src/unstaged_diff.rs b/crates/git_ui/src/unstaged_diff.rsindex 3e677353cf2..468cfd97a6e 100644--- a/crates/git_ui/src/unstaged_diff.rs+++ b/crates/git_ui/src/unstaged_diff.rs@@ -30,7 +30,7 @@ use util::ResultExt as _;use workspace::{ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,Workspace,- item::{Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},+ item::{Item, ItemEvent, ItemHandle, SaveOptions},searchable::SearchableItemHandle,};@@ -421,16 +421,6 @@ impl Item for UnstagedDiff {Some("Unstaged Changes".into())}- fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {- Label::new(self.tab_content_text(0, _cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {"Unstaged Changes".into()}diff --git a/crates/git_ui_core/src/file_diff_view.rs b/crates/git_ui_core/src/file_diff_view.rsindex 1d61075bcc3..4e1db897e3b 100644--- a/crates/git_ui_core/src/file_diff_view.rs+++ b/crates/git_ui_core/src/file_diff_view.rs@@ -8,8 +8,8 @@ use editor::{};use futures::{FutureExt, select_biased};use gpui::{- AnyElement, App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle,- Focusable, Font, IntoElement, Render, Task, WeakEntity, Window,+ App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle, Focusable, Font,+ IntoElement, Render, Task, WeakEntity, Window,};use language::{Buffer, HighlightedText, Point};use project::{Project, ProjectPath};@@ -21,11 +21,11 @@ use std::{sync::Arc,time::Duration,};-use ui::{Color, Icon, IconName, Label, LabelCommon as _, SharedString};+use ui::{Color, Icon, IconName, SharedString};use util::paths::PathExt as _;use workspace::{Item, ItemHandle as _, ItemNavHistory, ToolbarItemLocation, Workspace,- item::{ItemEvent, SaveOptions, TabContentParams},+ item::{ItemEvent, SaveOptions},searchable::SearchableItemHandle,};@@ -250,16 +250,6 @@ impl Item for FileDiffView {Some(Icon::new(IconName::Diff).color(Color::Muted))}- fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {- Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))- .color(if params.selected {- Color::Default- } else {- Color::Muted- })- .into_any_element()- }-fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {let title_text = |buffer: &Entity<Buffer>| {bufferdiff --git a/crates/picker/src/highlighted_match_with_paths.rs b/crates/picker/src/highlighted_match_with_paths.rsindex 62bae443124..5d155fc1a3c 100644--- a/crates/picker/src/highlighted_match_with_paths.rs+++ b/crates/picker/src/highlighted_match_with_paths.rs@@ -53,6 +53,7 @@ impl HighlightedMatch {impl RenderOnce for HighlightedMatch {fn render(self, _window: &mut Window, _: &mut App) -> impl IntoElement {HighlightedLabel::new(self.text, self.highlight_positions)+ .single_line().color(self.color).truncate()}@@ -62,6 +63,7 @@ impl HighlightedMatchWithPaths {pub fn render_paths_children(&mut self, element: Div) -> Div {element.children(self.paths.clone().into_iter().map(|path| {HighlightedLabel::new(path.text, path.highlight_positions)+ .single_line().size(LabelSize::Small).color(Color::Muted)}))diff --git a/crates/tabular_data_preview/src/renderer/table_header.rs b/crates/tabular_data_preview/src/renderer/table_header.rsindex 3481664895e..8811284e08a 100644--- a/crates/tabular_data_preview/src/renderer/table_header.rs+++ b/crates/tabular_data_preview/src/renderer/table_header.rs@@ -1,4 +1,5 @@use std::{+ borrow::Cow,collections::HashMap,sync::{Arc,@@ -13,7 +14,7 @@ use gpui::{use picker::{Picker, PickerDelegate};use ui::{Color, GradientFade, HighlightedLabel, Icon, IconButton, IconName, IconSize, Label, LabelSize,- ListItem, ListItemSpacing, PopoverMenu, Tooltip, prelude::*,+ ListItem, ListItemSpacing, PopoverMenu, Tooltip, prelude::*, utils::replace_control_characters,};use crate::{@@ -560,12 +561,19 @@ impl TabularDataPreviewPane {.min_w_0().overflow_hidden().whitespace_nowrap();+ // Column names come from the file being previewed, so they may+ // hold control characters. Show stand-ins for those, but keep+ // the real name for copying.+ let displayed_header = match replace_control_characters(&header_text) {+ Cow::Borrowed(_) => header_text.clone(),+ Cow::Owned(replaced) => SharedString::from(replaced),+ };with_copy_on_right_click(header_text_cell,- header_text.clone(),+ header_text,"Right click to copy column name",)- .child(header_text)+ .child(displayed_header)}).child(GradientFade::new(base_bg, base_bg, base_bg)diff --git a/crates/terminal_view/src/terminal_view.rs b/crates/terminal_view/src/terminal_view.rsindex 6ef5121136c..1a9b84a714b 100644--- a/crates/terminal_view/src/terminal_view.rs+++ b/crates/terminal_view/src/terminal_view.rs@@ -1526,6 +1526,7 @@ impl Item for TerminalView {.relative().child(Label::new(title)+ .single_line().color(params.text_color()).when(self.is_renaming(), |this| this.alpha(0.)),)diff --git a/crates/ui/src/components/label/highlighted_label.rs b/crates/ui/src/components/label/highlighted_label.rsindex 0dd28112e89..5d15d4858e2 100644--- a/crates/ui/src/components/label/highlighted_label.rs+++ b/crates/ui/src/components/label/highlighted_label.rs@@ -3,6 +3,7 @@ use std::ops::Range;use gpui::{FontWeight, HighlightStyle, StyleRefinement, StyledText};use gpui_util::debug_panic;+use crate::utils::replace_control_characters_remapping_offsets;use crate::{LabelCommon, LabelLike, LabelSize, LineHeightStyle, prelude::*};#[derive(IntoElement, RegisterComponent)]@@ -166,6 +167,16 @@ impl LabelCommon for HighlightedLabel {}fn single_line(mut self) -> Self {+ // The highlight indices are byte offsets into the label, and every+ // stand-in is wider in bytes than the character it replaces, so they+ // have to move with the text. Left alone they would index into the+ // middle of a character, which panics when the highlight ranges are+ // built — in release builds too.+ if let Some(replaced) =+ replace_control_characters_remapping_offsets(&self.label, &mut self.highlight_indices)+ {+ self.label = SharedString::from(replaced);+ }self.base = self.base.single_line();self}@@ -326,3 +337,55 @@ impl Component for HighlightedLabel {.into_any_element()}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_single_line_replaces_control_characters() {+ let label = HighlightedLabel::new("a\nb\rc\td", Vec::new()).single_line();+ assert_eq!(label.text(), "a⏎b␍c␉d");+ }++ #[test]+ fn test_single_line_moves_highlights_with_the_text() {+ // Highlighting "a" and "b" in "a\tb": "b" sits at byte 2 before the+ // replacement and at byte 4 after it, the stand-in being three bytes.+ let label = HighlightedLabel::new("a\tb", vec![0, 2]).single_line();+ assert_eq!(label.text(), "a␉b");+ assert_eq!(label.highlight_indices(), &[0, 4]);+ }++ #[test]+ fn test_single_line_keeps_highlights_on_character_boundaries() {+ // Highlighting every character of a name full of control characters is+ // what would panic while building the highlight ranges if the offsets+ // were left pointing into the old text.+ let text = "a\tb\nc\rd";+ let indices: Vec<usize> = text.char_indices().map(|(ix, _)| ix).collect();+ let label = HighlightedLabel::new(text, indices).single_line();+ for index in label.highlight_indices() {+ assert!(+ label.text().is_char_boundary(*index),+ "index {index} is not a boundary of {:?}",+ label.text(),+ );+ }+ }++ #[test]+ fn test_single_line_leaves_printable_text_alone() {+ let label = HighlightedLabel::new("main.rs", vec![0, 5]).single_line();+ assert_eq!(label.text(), "main.rs");+ assert_eq!(label.highlight_indices(), &[0, 5]);+ }++ #[test]+ fn test_replacement_only_happens_on_single_line() {+ // Multi-line labels are a legitimate use, so nothing is substituted+ // unless the caller asked for a single line.+ let label = HighlightedLabel::new("a\nb", vec![0]);+ assert_eq!(label.text(), "a\nb");+ }+}diff --git a/crates/ui/src/components/label/label.rs b/crates/ui/src/components/label/label.rsindex 264049d45fc..fe3ab1923e4 100644--- a/crates/ui/src/components/label/label.rs+++ b/crates/ui/src/components/label/label.rs@@ -1,5 +1,7 @@+use std::borrow::Cow;use std::ops::Range;+use crate::utils::replace_control_characters;use crate::{LabelLike, prelude::*};use gpui::{HighlightStyle, StyleRefinement, StyledText};@@ -239,7 +241,9 @@ impl LabelCommon for Label {}fn single_line(mut self) -> Self {- self.label = SharedString::from(self.label.replace('\n', "⏎"));+ if let Cow::Owned(replaced) = replace_control_characters(&self.label) {+ self.label = SharedString::from(replaced);+ }self.base = self.base.single_line();self}@@ -327,6 +331,20 @@ fn parse_backtick_spans(text: &str) -> Option<(SharedString, Vec<Range<usize>>)>mod tests {use super::*;+ #[test]+ fn test_single_line_replaces_control_characters() {+ // File names are allowed to contain these, and rendering them verbatim+ // breaks the layout of tabs and project panel entries.+ let label = Label::new("a\nb\rc\td").single_line();+ assert_eq!(label.label, "a⏎b␍c␉d");+ }++ #[test]+ fn test_single_line_leaves_printable_text_alone() {+ let label = Label::new("main.rs").single_line();+ assert_eq!(label.label, "main.rs");+ }+#[test]fn test_parse_backtick_spans_no_backticks() {assert_eq!(parse_backtick_spans("plain text"), None);diff --git a/crates/ui/src/utils.rs b/crates/ui/src/utils.rsindex d88bf4a45e0..42ed0b62405 100644--- a/crates/ui/src/utils.rs+++ b/crates/ui/src/utils.rs@@ -6,6 +6,7 @@ use theme::ActiveTheme;mod apca_contrast;mod color_contrast;mod constants;+mod control_characters;mod corner_solver;mod format_distance;mod search_input;@@ -14,6 +15,7 @@ mod with_rem_size;pub use apca_contrast::*;pub use color_contrast::*;pub use constants::*;+pub use control_characters::*;pub use corner_solver::{CornerSolver, inner_corner_radius};pub use format_distance::*;pub use search_input::*;diff --git a/crates/ui/src/utils/control_characters.rs b/crates/ui/src/utils/control_characters.rsnew file mode 100644index 00000000000..6604efd63ea--- /dev/null+++ b/crates/ui/src/utils/control_characters.rs@@ -0,0 +1,267 @@+//! Rendering of control characters that would otherwise be invisible.++use std::borrow::Cow;++/// The stand-in used for a line feed (`\n`).+///+/// This is the symbol Zed has always used for line feeds in single-line labels,+/// so text containing `\n` keeps rendering the way it used to.+const LINE_FEED_SYMBOL: char = '⏎';++/// Start of the Unicode "Control Pictures" block (`U+2400`), which holds one+/// printable stand-in per C0 control character, in code point order. So the+/// stand-in for a control character is `U+2400 + <its code point>`.+const CONTROL_PICTURES_START: u32 = 0x2400;++/// The stand-in for `DEL` (`U+007F`), which sits outside the contiguous range+/// covered by [`CONTROL_PICTURES_START`].+const DELETE_SYMBOL: char = '␡';++/// Returns the printable stand-in for a control character, or `None` if the+/// character is already printable.+///+/// C1 controls (`U+0080..=U+009F`) are deliberately left alone: they have no+/// Control Pictures equivalent to map onto.+fn printable_substitute(character: char) -> Option<char> {+ match character {+ '\n' => Some(LINE_FEED_SYMBOL),+ '\x7f' => Some(DELETE_SYMBOL),+ character if character.is_ascii_control() => {+ char::from_u32(CONTROL_PICTURES_START + character as u32)+ }+ _ => None,+ }+}++/// Replaces control characters with printable stand-ins, so that text+/// containing them stays legible instead of collapsing the line it is rendered+/// on.+///+/// File names are allowed to contain characters like `\n`, `\r` and `\t` on+/// most platforms, and rendering those verbatim breaks the layout of whatever+/// is displaying them. Every stand-in is a single character, so byte offsets+/// change but character offsets are preserved.+///+/// The input is returned untouched when it holds no control characters, which+/// is the overwhelmingly common case.+///+/// # Examples+///+/// ```+/// use ui::utils::replace_control_characters;+///+/// assert_eq!(replace_control_characters("main.rs"), "main.rs");+/// assert_eq!(replace_control_characters("two\nlines.rs"), "two⏎lines.rs");+/// assert_eq!(replace_control_characters("tab\there.rs"), "tab␉here.rs");+/// ```+pub fn replace_control_characters(text: &str) -> Cow<'_, str> {+ let Some(first_control_character) = text.find(|character: char| character.is_ascii_control())+ else {+ return Cow::Borrowed(text);+ };++ let (printable_prefix, rest) = text.split_at(first_control_character);+ let mut replaced = String::with_capacity(text.len());+ replaced.push_str(printable_prefix);+ for character in rest.chars() {+ match printable_substitute(character) {+ Some(substitute) => replaced.push(substitute),+ None => replaced.push(character),+ }+ }++ Cow::Owned(replaced)+}++/// Like [`replace_control_characters`], but also moves the given byte offsets+/// into the replaced string, and returns `None` when nothing was replaced.+///+/// Callers that carry byte offsets into the text — highlight positions, for+/// instance — cannot use [`replace_control_characters`] on its own: every+/// stand-in is wider in bytes than the character it replaces, so offsets past+/// the first replacement would land inside a character. Indexing a `str` at+/// such an offset panics in release builds too, so remapping is not optional.+///+/// Each offset must sit on a character boundary. Offsets past the end of the+/// text are clamped to the end of the replaced string.+///+/// # Examples+///+/// ```+/// use ui::utils::replace_control_characters_remapping_offsets;+///+/// // The offset of "b" moves from 2 to 4, the stand-in being three bytes wide.+/// let mut offsets = vec![0, 2];+/// let replaced = replace_control_characters_remapping_offsets("a\tb", &mut offsets);+/// assert_eq!(replaced.as_deref(), Some("a␉b"));+/// assert_eq!(offsets, vec![0, 4]);+/// ```+pub fn replace_control_characters_remapping_offsets(+ text: &str,+ offsets: &mut [usize],+) -> Option<String> {+ // Control characters are single bytes below 0x80, so scanning raw bytes+ // cannot mistake a UTF-8 continuation byte for one.+ if !text.bytes().any(|byte| byte.is_ascii_control()) {+ return None;+ }++ // Maps every byte offset in `text` to its offset in the replaced string.+ // Only entries on character boundaries are filled in, which is all callers+ // are allowed to ask about.+ let mut moved = vec![0; text.len() + 1];+ let mut replaced = String::with_capacity(text.len());+ for (offset, character) in text.char_indices() {+ moved[offset] = replaced.len();+ match printable_substitute(character) {+ Some(substitute) => replaced.push(substitute),+ None => replaced.push(character),+ }+ }+ moved[text.len()] = replaced.len();++ for offset in offsets {+ debug_assert!(+ *offset > text.len() || text.is_char_boundary(*offset),+ "offset {offset} is not on a character boundary of {text:?}",+ );+ *offset = moved.get(*offset).copied().unwrap_or(replaced.len());+ }++ Some(replaced)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_printable_text_is_not_reallocated() {+ assert!(matches!(+ replace_control_characters("main.rs"),+ Cow::Borrowed("main.rs")+ ));+ assert!(matches!(replace_control_characters(""), Cow::Borrowed("")));+ }++ #[test]+ fn test_replaces_control_characters() {+ assert_eq!(replace_control_characters("a\nb"), "a⏎b");+ assert_eq!(replace_control_characters("a\rb"), "a␍b");+ assert_eq!(replace_control_characters("a\tb"), "a␉b");+ assert_eq!(replace_control_characters("a\0b"), "a␀b");+ assert_eq!(replace_control_characters("a\x7fb"), "a␡b");+ }++ #[test]+ fn test_replaces_every_occurrence() {+ assert_eq!(replace_control_characters("\r\n\t"), "␍⏎␉");+ assert_eq!(replace_control_characters("a\nb\nc"), "a⏎b⏎c");+ }++ #[test]+ fn test_preserves_non_control_characters() {+ // Multi-byte characters must survive the scan intact, including when+ // they sit next to a character that is replaced.+ assert_eq!(replace_control_characters("é\nü"), "é⏎ü");+ assert_eq!(replace_control_characters("🚀"), "🚀");+ assert_eq!(replace_control_characters("🚀\t🚀"), "🚀␉🚀");+ }++ #[test]+ fn test_character_count_is_preserved() {+ for text in ["a\nb", "\r\n\t", "a\x7fb", "é\nü"] {+ assert_eq!(+ replace_control_characters(text).chars().count(),+ text.chars().count(),+ );+ }+ }++ #[test]+ fn test_leaves_c1_control_characters_alone() {+ // These have no Control Pictures equivalent, so they are passed through.+ assert_eq!(replace_control_characters("a\u{0085}b"), "a\u{0085}b");+ }++ #[test]+ fn test_printable_text_is_left_alone_when_remapping() {+ let mut offsets = vec![0, 3];+ assert_eq!(+ replace_control_characters_remapping_offsets("main.rs", &mut offsets),+ None,+ );+ assert_eq!(offsets, vec![0, 3], "offsets must not move");+ }++ #[test]+ fn test_remaps_offsets_after_a_replacement() {+ // Each stand-in is two bytes wider than what it replaces, so offsets+ // shift by two per replacement that precedes them.+ let mut offsets = vec![0, 1, 2];+ let replaced = replace_control_characters_remapping_offsets("a\tb", &mut offsets).unwrap();+ assert_eq!(replaced, "a␉b");+ assert_eq!(offsets, vec![0, 1, 4]);+ }++ #[test]+ fn test_remaps_offsets_across_several_replacements() {+ let mut offsets = vec![0, 2, 4];+ let replaced =+ replace_control_characters_remapping_offsets("a\tb\tc", &mut offsets).unwrap();+ assert_eq!(replaced, "a␉b␉c");+ assert_eq!(offsets, vec![0, 4, 8]);+ }++ #[test]+ fn test_remaps_offsets_around_multi_byte_characters() {+ // "é" is already two bytes, so the mapping must count real byte widths+ // rather than assume one byte per character.+ let mut offsets = vec![0, 2, 5];+ let replaced = replace_control_characters_remapping_offsets("é\tü", &mut offsets).unwrap();+ assert_eq!(replaced, "é␉ü");+ assert_eq!(offsets, vec![0, 2, 5 + 2]);+ }++ #[test]+ fn test_remapped_offsets_stay_on_character_boundaries() {+ for text in ["a\nb", "\r\n\t", "é\nü", "🚀\t🚀", "a\x7fb"] {+ let mut offsets: Vec<usize> = text.char_indices().map(|(ix, _)| ix).collect();+ let replaced =+ replace_control_characters_remapping_offsets(text, &mut offsets).unwrap();+ for offset in offsets {+ assert!(+ replaced.is_char_boundary(offset),+ "offset {offset} is not a boundary of {replaced:?} (from {text:?})",+ );+ }+ }+ }++ #[test]+ fn test_remaps_the_end_offset() {+ // Highlight ranges may end at the very end of the text.+ let mut offsets = vec!["a\tb".len()];+ let replaced = replace_control_characters_remapping_offsets("a\tb", &mut offsets).unwrap();+ assert_eq!(offsets, vec![replaced.len()]);+ }++ #[test]+ fn test_clamps_offsets_past_the_end() {+ let mut offsets = vec![999];+ let replaced = replace_control_characters_remapping_offsets("a\tb", &mut offsets).unwrap();+ assert_eq!(offsets, vec![replaced.len()]);+ }++ #[test]+ fn test_remapping_agrees_with_the_borrowing_variant() {+ for text in ["main.rs", "a\nb", "\r\n\t", "é\nü", "🚀\t🚀"] {+ let remapped = replace_control_characters_remapping_offsets(text, &mut []);+ let borrowed = replace_control_characters(text);+ match remapped {+ Some(replaced) => assert_eq!(replaced, borrowed.as_ref()),+ None => assert!(matches!(borrowed, Cow::Borrowed(_))),+ }+ }+ }+}diff --git a/crates/workspace/src/item.rs b/crates/workspace/src/item.rsindex 9b4ad5dbbb6..4a52b9099f6 100644--- a/crates/workspace/src/item.rs+++ b/crates/workspace/src/item.rs@@ -178,6 +178,7 @@ pub trait Item: Focusable + EventEmitter<Self::Event> + Render + Sized {let text = self.tab_content_text(params.detail.unwrap_or_default(), cx);Label::new(text)+ .single_line().color(params.text_color()).into_any_element()}