Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

tab_switcher: Middle-truncate long picker filenames (#59072)

saberoueslati03a8544040ff
diff --git a/crates/editor/src/items.rs b/crates/editor/src/items.rs
index 4156617ef55..a5fc5b2b991 100644
--- a/crates/editor/src/items.rs
+++ b/crates/editor/src/items.rs
@@ -783,11 +783,20 @@ impl Item for Editor {
h_flex()
.gap_2()
+ .when(params.truncate_title_middle, |this| {
+ this.w_full().min_w_0().overflow_hidden()
+ })
.child(
- Label::new(util::truncate_and_trailoff(
- &self.title(cx),
- params.max_title_len.unwrap_or(MAX_TAB_TITLE_LEN),
- ))
+ Label::new(if params.truncate_title_middle {
+ self.title(cx).to_string()
+ } else {
+ util::truncate_and_trailoff(
+ &self.title(cx),
+ params.max_title_len.unwrap_or(MAX_TAB_TITLE_LEN),
+ )
+ })
+ .when(params.truncate_title_middle, |this| this.truncate_middle())
+ .when(params.truncate_title_middle, |this| this.flex_1())
.color(label_color)
.when(params.preview, |this| this.italic())
.when(was_deleted, |this| this.strikethrough()),
@@ -796,6 +805,9 @@ impl Item for Editor {
this.child(
Label::new(description)
.size(LabelSize::XSmall)
+ .when(params.truncate_title_middle, |this| {
+ this.truncate_start().flex_shrink()
+ })
.color(Color::Muted),
)
})
diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs
index f45f81a6edb..a4feaf29523 100644
--- a/crates/file_finder/src/file_finder.rs
+++ b/crates/file_finder/src/file_finder.rs
@@ -1876,10 +1876,13 @@ impl PickerDelegate for FileFinderDelegate {
.toggle_state(selected)
.child(
h_flex()
+ .w_full()
+ .min_w_0()
+ .overflow_hidden()
.gap_2()
.py_px()
- .child(file_name_label)
- .child(full_path_label),
+ .child(file_name_label.truncate_middle().flex_1())
+ .child(full_path_label.truncate_start().flex_shrink()),
),
)
}
diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rs
index ee4daa38386..ae37d3fdd91 100644
--- a/crates/gpui/src/elements/text.rs
+++ b/crates/gpui/src/elements/text.rs
@@ -669,6 +669,7 @@ impl TextLayout {
match text_overflow {
TextOverflow::Truncate(s) => (width, s, TruncateFrom::End),
TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start),
+ TextOverflow::TruncateMiddle(s) => (width, s, TruncateFrom::Middle),
}
} else {
(None, "".into(), TruncateFrom::End)
diff --git a/crates/gpui/src/style.rs b/crates/gpui/src/style.rs
index 54e09bc37dd..2853778d997 100644
--- a/crates/gpui/src/style.rs
+++ b/crates/gpui/src/style.rs
@@ -375,6 +375,10 @@ pub enum TextOverflow {
/// displaying the provided string at the beginning (e.g., "…ong text here").
/// Typically more adequate for file paths where the end is more important than the beginning.
TruncateStart(SharedString),
+ /// Truncate the text in the middle when it doesn't fit, preserving both the start and end
+ /// of the string (e.g., "long fi…name.rs"). Useful for filenames where both the prefix
+ /// and the extension are important context.
+ TruncateMiddle(SharedString),
}
/// How to align text within the element
diff --git a/crates/gpui/src/styled.rs b/crates/gpui/src/styled.rs
index 3004e157e47..901e64d5166 100644
--- a/crates/gpui/src/styled.rs
+++ b/crates/gpui/src/styled.rs
@@ -99,6 +99,14 @@ pub trait Styled: Sized {
self
}
+ /// Sets the truncate overflowing text with an ellipsis (…) in the middle if needed.
+ /// Preserves the beginning and end of the text. Useful for filenames.
+ /// Note: This doesn't exist in Tailwind CSS.
+ fn text_ellipsis_middle(mut self) -> Self {
+ self.text_style().text_overflow = Some(TextOverflow::TruncateMiddle(ELLIPSIS));
+ self
+ }
+
/// Sets the text overflow behavior of the element.
fn text_overflow(mut self, overflow: TextOverflow) -> Self {
self.text_style().text_overflow = Some(overflow);
diff --git a/crates/gpui/src/text_system/line_wrapper.rs b/crates/gpui/src/text_system/line_wrapper.rs
index 3335e7b31d1..dd6d2d98707 100644
--- a/crates/gpui/src/text_system/line_wrapper.rs
+++ b/crates/gpui/src/text_system/line_wrapper.rs
@@ -9,6 +9,8 @@ pub enum TruncateFrom {
Start,
/// Truncate text from the end.
End,
+ /// Truncate text from the middle, preserving the start and end.
+ Middle,
}
/// The GPUI line wrapper, used to wrap lines of text to a given width.
@@ -179,11 +181,69 @@ impl LineWrapper {
}
}
}
+ TruncateFrom::Middle => {}
}
None
}
+ fn should_truncate_line_middle(
+ &mut self,
+ line: &str,
+ truncate_width: Pixels,
+ truncation_affix: &str,
+ ) -> Option<(usize, usize)> {
+ let suffix_width = truncation_affix
+ .chars()
+ .map(|c| self.width_for_char(c))
+ .fold(px(0.0), |a, x| a + x);
+
+ let total_width: Pixels = line
+ .chars()
+ .map(|c| self.width_for_char(c))
+ .fold(px(0.0), |a, x| a + x);
+
+ if total_width <= truncate_width {
+ return None;
+ }
+
+ let content_budget = truncate_width - suffix_width;
+ if content_budget <= px(0.) {
+ return Some((0, line.len()));
+ }
+
+ let front_budget = content_budget * (2.0 / 3.0);
+ let back_budget = content_budget - front_budget;
+
+ let mut front_width = px(0.);
+ let mut front_end_ix = 0usize;
+ for (ix, c) in line.char_indices() {
+ let char_width = self.width_for_char(c);
+ if front_width + char_width > front_budget {
+ break;
+ }
+ front_width += char_width;
+ front_end_ix = ix + c.len_utf8();
+ }
+
+ let mut back_width = px(0.);
+ let mut back_start_ix = line.len();
+ for (ix, c) in line.char_indices().rev() {
+ let char_width = self.width_for_char(c);
+ if back_width + char_width > back_budget {
+ break;
+ }
+ back_width += char_width;
+ back_start_ix = ix;
+ }
+
+ if front_end_ix >= back_start_ix {
+ return Some((0, line.len()));
+ }
+
+ Some((front_end_ix, back_start_ix))
+ }
+
/// Truncate a line of text to the given width with this wrapper's font and font size.
pub fn truncate_line<'a>(
&mut self,
@@ -193,6 +253,28 @@ impl LineWrapper {
runs: &'a [TextRun],
truncate_from: TruncateFrom,
) -> (SharedString, Cow<'a, [TextRun]>) {
+ if truncate_from == TruncateFrom::Middle {
+ if let Some((front_end_ix, back_start_ix)) =
+ self.should_truncate_line_middle(&line, truncate_width, truncation_affix)
+ {
+ let result = SharedString::from(format!(
+ "{}{truncation_affix}{}",
+ &line[..front_end_ix],
+ &line[back_start_ix..]
+ ));
+ let mut runs = runs.to_vec();
+ update_runs_after_middle_truncation(
+ truncation_affix,
+ &mut runs,
+ front_end_ix,
+ back_start_ix,
+ );
+ return (result, Cow::Owned(runs));
+ } else {
+ return (line, Cow::Borrowed(runs));
+ }
+ }
+
if let Some(truncate_ix) =
self.should_truncate_line(&line, truncate_width, truncation_affix, truncate_from)
{
@@ -206,6 +288,7 @@ impl LineWrapper {
line[..truncate_ix]
.trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation())
)),
+ TruncateFrom::Middle => unreachable!("Middle truncation is handled above"),
};
let mut runs = runs.to_vec();
update_runs_after_truncation(&result, truncation_affix, &mut runs, truncate_from);
@@ -242,6 +325,9 @@ impl LineWrapper {
truncate_from,
);
}
+ if truncate_from == TruncateFrom::Middle {
+ return self.truncate_line(text, wrap_width, truncation_affix, runs, truncate_from);
+ }
let affix_width: Pixels = truncation_affix
.chars()
@@ -448,7 +534,71 @@ fn update_runs_after_truncation(
}
}
}
+ TruncateFrom::Middle => {
+ unreachable!("Middle truncation calls this function with TruncateFrom::End directly")
+ }
+ }
+}
+
+fn update_runs_after_middle_truncation(
+ ellipsis: &str,
+ runs: &mut Vec<TextRun>,
+ front_end_ix: usize,
+ back_start_ix: usize,
+) {
+ let original_runs = std::mem::take(runs);
+ let mut result_runs: Vec<TextRun> = Vec::with_capacity(original_runs.len());
+
+ // Front segment [0, front_end_ix) + ellipsis: walk forward until the run
+ // that straddles or ends at front_end_ix, then extend that run's length
+ // to include the ellipsis.
+ let mut front_remaining = front_end_ix;
+ let mut front_done = false;
+ for run in &original_runs {
+ if front_done {
+ break;
+ }
+ if run.len <= front_remaining {
+ result_runs.push(run.clone());
+ front_remaining -= run.len;
+ } else {
+ let mut partial = run.clone();
+ partial.len = front_remaining + ellipsis.len();
+ result_runs.push(partial);
+ front_done = true;
+ }
+ }
+ if !front_done {
+ // front_end_ix landed exactly on a run boundary; append ellipsis to
+ // the last front run (or, if the front is empty, to the first back run).
+ if let Some(last) = result_runs.last_mut() {
+ last.len += ellipsis.len();
+ } else if let Some(first) = original_runs.first() {
+ let mut affix_run = first.clone();
+ affix_run.len = ellipsis.len();
+ result_runs.push(affix_run);
+ }
+ }
+
+ // Back segment [back_start_ix, original.len()): skip runs entirely in the
+ // removed middle, keep the rest.
+ let mut byte_pos = 0usize;
+ for run in &original_runs {
+ let run_end = byte_pos + run.len;
+ if run_end > back_start_ix {
+ if byte_pos < back_start_ix {
+ // Run straddles back_start_ix; keep only the tail.
+ let mut partial = run.clone();
+ partial.len = run_end - back_start_ix;
+ result_runs.push(partial);
+ } else {
+ result_runs.push(run.clone());
+ }
+ }
+ byte_pos = run_end;
}
+
+ *runs = result_runs;
}
/// A fragment of a line that can be wrapped.
@@ -1275,6 +1425,81 @@ mod tests {
);
}
+ #[test]
+ fn test_truncate_line_middle() {
+ let mut wrapper = build_wrapper();
+
+ // No truncation when text fits within a very wide budget.
+ let short_text = "hello world";
+ let runs = generate_test_runs(&[short_text.len()]);
+ let (result, result_runs) = wrapper.truncate_line(
+ short_text.into(),
+ px(10000.),
+ "…",
+ &runs,
+ TruncateFrom::Middle,
+ );
+ assert_eq!(result.as_ref(), short_text);
+ assert_eq!(result_runs.len(), 1);
+ assert_eq!(result_runs[0].len, short_text.len());
+
+ // Basic middle truncation: long string with px(100.) budget.
+ let long_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
+ let runs = generate_test_runs(&[long_text.len()]);
+ let (result, _result_runs) =
+ wrapper.truncate_line(long_text.into(), px(100.), "…", &runs, TruncateFrom::Middle);
+ assert!(
+ result.contains('…'),
+ "Middle-truncated result should contain '…', got: '{}'",
+ result
+ );
+ assert!(
+ result.chars().count() < long_text.chars().count(),
+ "Middle-truncated result should be shorter than original"
+ );
+ assert_eq!(
+ result.chars().next(),
+ long_text.chars().next(),
+ "Result should start with the same first character as original"
+ );
+ assert_eq!(
+ result.chars().last(),
+ long_text.chars().last(),
+ "Result should end with the same last character as original"
+ );
+
+ // Degenerate case: budget so narrow that middle truncation cannot find a valid split.
+ // Still show the truncation affix instead of returning the original overflowing text.
+ let text = "abcdef";
+ let runs = generate_test_runs(&[text.len()]);
+ let (result, result_runs) =
+ wrapper.truncate_line(text.into(), px(1.), "…", &runs, TruncateFrom::Middle);
+ assert_eq!(result.as_ref(), "…");
+ assert_eq!(result_runs.len(), 1);
+ assert_eq!(result_runs[0].len, "…".len());
+
+ // Run adjustment correctness: multiple runs across the string.
+ // Verify that the returned runs' lengths sum to result.len().
+ let multi_run_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
+ let run_lens = [20, 20, multi_run_text.len() - 40];
+ let runs = generate_test_runs(&run_lens);
+ let (result, result_runs) = wrapper.truncate_line(
+ multi_run_text.into(),
+ px(100.),
+ "…",
+ &runs,
+ TruncateFrom::Middle,
+ );
+ let total_run_len: usize = result_runs.iter().map(|r| r.len).sum();
+ assert_eq!(
+ total_run_len,
+ result.len(),
+ "Sum of run lengths ({}) should equal result byte length ({})",
+ total_run_len,
+ result.len()
+ );
+ }
+
#[test]
fn test_multiline_truncation_trailing_newline() {
let mut wrapper = build_wrapper();
diff --git a/crates/tab_switcher/src/tab_switcher.rs b/crates/tab_switcher/src/tab_switcher.rs
index 9f9f706780b..7edaaf46c75 100644
--- a/crates/tab_switcher/src/tab_switcher.rs
+++ b/crates/tab_switcher/src/tab_switcher.rs
@@ -831,6 +831,7 @@ impl PickerDelegate for TabSwitcherDelegate {
preview: tab_match.preview,
deemphasized: false,
max_title_len: Some(usize::MAX),
+ truncate_title_middle: true,
};
let label = tab_match.item.tab_content(params, window, cx);
@@ -875,7 +876,7 @@ impl PickerDelegate for TabSwitcherDelegate {
.spacing(ListItemSpacing::Sparse)
.inset(true)
.toggle_state(selected)
- .child(h_flex().w_full().child(label))
+ .child(h_flex().w_full().min_w_0().overflow_hidden().child(label))
.start_slot::<DecoratedIcon>(icon)
.map(|el| {
if self.selected_index == ix {
diff --git a/crates/ui/src/components/label/highlighted_label.rs b/crates/ui/src/components/label/highlighted_label.rs
index 2cac321ab64..0dd28112e89 100644
--- a/crates/ui/src/components/label/highlighted_label.rs
+++ b/crates/ui/src/components/label/highlighted_label.rs
@@ -77,6 +77,12 @@ impl HighlightedLabel {
self.base = self.base.truncate_start();
self
}
+
+ /// Truncates overflowing text with an ellipsis (`…`) in the middle if needed.
+ pub fn truncate_middle(mut self) -> Self {
+ self.base = self.base.truncate_middle();
+ self
+ }
}
impl HighlightedLabel {
diff --git a/crates/ui/src/components/label/label.rs b/crates/ui/src/components/label/label.rs
index 8b98817b050..264049d45fc 100644
--- a/crates/ui/src/components/label/label.rs
+++ b/crates/ui/src/components/label/label.rs
@@ -74,6 +74,12 @@ impl Label {
self
}
+ /// Truncates overflowing text with an ellipsis (`…`) in the middle if needed.
+ pub fn truncate_middle(mut self) -> Self {
+ self.base = self.base.truncate_middle();
+ self
+ }
+
/// Wraps the text and truncates it with an ellipsis (`…`) at the end of
/// the last visible line if it exceeds the given number of lines.
pub fn line_clamp(mut self, lines: usize) -> Self {
diff --git a/crates/ui/src/components/label/label_like.rs b/crates/ui/src/components/label/label_like.rs
index 4218c5d1fe7..ebc6c9b8250 100644
--- a/crates/ui/src/components/label/label_like.rs
+++ b/crates/ui/src/components/label/label_like.rs
@@ -89,6 +89,7 @@ pub struct LabelLike {
single_line: bool,
truncate: bool,
truncate_start: bool,
+ truncate_middle: bool,
}
impl Default for LabelLike {
@@ -115,6 +116,7 @@ impl LabelLike {
single_line: false,
truncate: false,
truncate_start: false,
+ truncate_middle: false,
}
}
}
@@ -135,6 +137,13 @@ impl LabelLike {
self
}
+ /// Truncates overflowing text with an ellipsis (`…`) in the middle if needed.
+ /// Preserves the start and end of the text. Useful for filenames.
+ pub fn truncate_middle(mut self) -> Self {
+ self.truncate_middle = true;
+ self
+ }
+
/// Wraps the text and truncates it with an ellipsis (`…`) at the end of
/// the last visible line if it exceeds the given number of lines.
pub fn line_clamp(mut self, lines: usize) -> Self {
@@ -262,6 +271,12 @@ impl RenderOnce for LabelLike {
.whitespace_nowrap()
.text_ellipsis_start()
})
+ .when(self.truncate_middle, |this| {
+ this.min_w_0()
+ .overflow_x_hidden()
+ .whitespace_nowrap()
+ .text_ellipsis_middle()
+ })
.text_color(color)
.font_weight(
self.weight
diff --git a/crates/workspace/src/item.rs b/crates/workspace/src/item.rs
index c2fbfc94463..9b4ad5dbbb6 100644
--- a/crates/workspace/src/item.rs
+++ b/crates/workspace/src/item.rs
@@ -135,6 +135,7 @@ pub struct TabContentParams {
pub deemphasized: bool,
/// Maximum character length for the title. None = use the item's own default (typically MAX_TAB_TITLE_LEN).
pub max_title_len: Option<usize>,
+ pub truncate_title_middle: bool,
}
impl TabContentParams {
diff --git a/crates/workspace/src/pane.rs b/crates/workspace/src/pane.rs
index a3d56abf19b..ea3091a6fff 100644
--- a/crates/workspace/src/pane.rs
+++ b/crates/workspace/src/pane.rs
@@ -2795,6 +2795,7 @@ impl Pane {
preview: is_preview,
deemphasized: !self.has_focus(window, cx),
max_title_len: None,
+ truncate_title_middle: false,
},
window,
cx,
@@ -4929,6 +4930,7 @@ impl Render for DraggedTab {
preview: false,
deemphasized: false,
max_title_len: None,
+ truncate_title_middle: false,
},
window,
cx,