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.

editor: Add support for customizable soft wrap indentation (#63468)

Aru Sahni4f70d91bda7e
diff --git a/assets/settings/default.json b/assets/settings/default.json
index c0e79ab1916..249100135bc 100644
--- a/assets/settings/default.json
+++ b/assets/settings/default.json
@@ -1648,6 +1648,12 @@
// 3. Soft wrap lines at the preferred line length or the editor width (whichever is smaller).
// "soft_wrap": "bounded",
"soft_wrap": "none",
+ // How to indent soft-wrapped continuation lines.
+ // "none" - start at column 0
+ // "same" - match original line's indentation (default)
+ // "extra_one" - same + 1 indent level
+ // "extra_two" - same + 2 indent levels
+ "soft_wrap_indent": "same",
// The column at which to soft-wrap lines, for buffers where soft-wrap
// is enabled.
"preferred_line_length": 80,
diff --git a/crates/editor/src/config.rs b/crates/editor/src/config.rs
index 6676a790a05..3e854935d3f 100644
--- a/crates/editor/src/config.rs
+++ b/crates/editor/src/config.rs
@@ -257,6 +257,10 @@ impl Editor {
wrap_guides
}
+ pub(super) fn soft_wrap_indent(&self, cx: &App) -> SoftWrapIndent {
+ self.buffer.read(cx).language_settings(cx).soft_wrap_indent
+ }
+
pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
let settings = self.buffer.read(cx).language_settings(cx);
let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
@@ -274,15 +278,23 @@ impl Editor {
// Called by the element. This method is not designed to be called outside of the editor
// element's layout code because it does not notify when rewrapping is computed synchronously.
pub(super) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
+ let indent = self.soft_wrap_indent(cx);
if self.is_empty(cx) {
self.placeholder_display_map
.as_ref()
.map_or(false, |display_map| {
- display_map.update(cx, |map, cx| map.set_wrap_width(width, cx))
+ display_map.update(cx, |map, cx| {
+ let wrap_width_changed = map.set_wrap_width(width, cx);
+ let indent_changed = map.set_soft_wrap_indent(indent, cx);
+ wrap_width_changed || indent_changed
+ })
})
} else {
- self.display_map
- .update(cx, |map, cx| map.set_wrap_width(width, cx))
+ self.display_map.update(cx, |map, cx| {
+ let wrap_width_changed = map.set_wrap_width(width, cx);
+ let indent_changed = map.set_soft_wrap_indent(indent, cx);
+ wrap_width_changed || indent_changed
+ })
}
}
diff --git a/crates/editor/src/display_map.rs b/crates/editor/src/display_map.rs
index f65dbf40524..4a864006c74 100644
--- a/crates/editor/src/display_map.rs
+++ b/crates/editor/src/display_map.rs
@@ -100,7 +100,7 @@ use gpui::{
};
use language::{
LanguageAwareStyling, Point, Subscription as BufferSubscription,
- language_settings::{AllLanguageSettings, LanguageSettings},
+ language_settings::{AllLanguageSettings, LanguageSettings, SoftWrapIndent},
};
use multi_buffer::{
@@ -1249,6 +1249,11 @@ impl DisplayMap {
.update(cx, |map, cx| map.set_wrap_width(width, cx))
}
+ pub fn set_soft_wrap_indent(&self, indent: SoftWrapIndent, cx: &mut Context<Self>) -> bool {
+ self.wrap_map
+ .update(cx, |map, cx| map.set_soft_wrap_indent(indent, cx))
+ }
+
#[instrument(skip_all)]
pub fn update_fold_widths(
&mut self,
diff --git a/crates/editor/src/display_map/wrap_map.rs b/crates/editor/src/display_map/wrap_map.rs
index 7899d620751..b7501acdd2d 100644
--- a/crates/editor/src/display_map/wrap_map.rs
+++ b/crates/editor/src/display_map/wrap_map.rs
@@ -9,14 +9,16 @@ use super::{
use collections::HashMap;
use futures_lite::future::yield_now;
use gpui::{
- App, AppContext as _, Context, Entity, Font, FontId, LineWrapper, Pixels, Task, TextSystem,
+ App, AppContext as _, Context, Entity, Font, FontId, IndentAdjustment, LineWrapper, Pixels,
+ Task, TextSystem,
};
-use language::{LanguageAwareStyling, Point};
+use language::{LanguageAwareStyling, Point, language_settings::SoftWrapIndent};
use multi_buffer::RowInfo;
use std::{
cmp,
collections::VecDeque,
mem,
+ num::NonZeroU32,
ops::Range,
sync::{Arc, LazyLock},
time::Duration,
@@ -46,6 +48,7 @@ pub struct WrapMap {
interpolated_edits: WrapPatch,
edits_since_sync: WrapPatch,
wrap_width: Option<Pixels>,
+ soft_wrap_indent: SoftWrapIndent,
background_task: Option<Task<()>>,
font_with_size: (Font, Pixels),
}
@@ -189,6 +192,7 @@ impl WrapMap {
let mut this = Self {
font_with_size: (font, font_size),
wrap_width: None,
+ soft_wrap_indent: SoftWrapIndent::default(),
pending_edits: Default::default(),
interpolated_edits: Default::default(),
edits_since_sync: Default::default(),
@@ -263,6 +267,21 @@ impl WrapMap {
true
}
+ #[ztracing::instrument(skip_all)]
+ pub fn set_soft_wrap_indent(&mut self, indent: SoftWrapIndent, cx: &mut Context<Self>) -> bool {
+ if indent == self.soft_wrap_indent {
+ return false;
+ }
+
+ self.soft_wrap_indent = indent;
+ self.rewrap(cx);
+ true
+ }
+
+ fn indent_adjustment(&self, tab_size: NonZeroU32) -> IndentAdjustment {
+ indent_adjustment_for(self.soft_wrap_indent, tab_size)
+ }
+
#[ztracing::instrument(skip_all)]
fn rewrap(&mut self, cx: &mut Context<Self>) {
self.background_task.take();
@@ -287,21 +306,24 @@ impl WrapMap {
if total_rows < WRAP_YIELD_ROW_INTERVAL {
let edits = gpui::block_on(new_snapshot.update(
- tab_snapshot,
+ tab_snapshot.clone(),
&tab_edits,
wrap_width,
+ self.indent_adjustment(tab_snapshot.tab_size),
&mut line_wrapper,
&mut fragment_builder,
));
self.snapshot = new_snapshot;
self.edits_since_sync = self.edits_since_sync.compose(&edits);
} else {
+ let indent_adjustment = self.indent_adjustment(tab_snapshot.tab_size);
let task = cx.background_spawn(async move {
let edits = new_snapshot
.update(
tab_snapshot,
&tab_edits,
wrap_width,
+ indent_adjustment,
&mut line_wrapper,
&mut fragment_builder,
)
@@ -391,10 +413,12 @@ impl WrapMap {
if update_passes + total_new_rows < WRAP_YIELD_ROW_INTERVAL {
let mut wrap_edits = Patch::default();
for (tab_snapshot, tab_edits) in pending_edits {
+ let indent_adjustment = self.indent_adjustment(tab_snapshot.tab_size);
let edits = gpui::block_on(snapshot.update(
tab_snapshot,
&tab_edits,
wrap_width,
+ indent_adjustment,
&mut line_wrapper,
&mut fragment_builder,
));
@@ -403,14 +427,18 @@ impl WrapMap {
self.snapshot = snapshot;
self.edits_since_sync = self.edits_since_sync.compose(&wrap_edits);
} else {
+ let soft_wrap_indent = self.soft_wrap_indent;
let update_task = cx.background_spawn(async move {
let mut edits = Patch::default();
for (tab_snapshot, tab_edits) in pending_edits {
+ let indent_adjustment =
+ indent_adjustment_for(soft_wrap_indent, tab_snapshot.tab_size);
let wrap_edits = snapshot
.update(
tab_snapshot,
&tab_edits,
wrap_width,
+ indent_adjustment,
&mut line_wrapper,
&mut fragment_builder,
)
@@ -558,6 +586,7 @@ impl WrapSnapshot {
new_tab_snapshot: TabSnapshot,
tab_edits: &[TabEdit],
wrap_width: Pixels,
+ indent_adjustment: IndentAdjustment,
line_wrapper: &mut LineWrapper,
fragment_builder: &mut LineFragmentBuilder,
) -> WrapPatch {
@@ -652,7 +681,9 @@ impl WrapSnapshot {
}
let mut prev_boundary_ix = 0;
- for boundary in line_wrapper.wrap_line(&line_fragments, wrap_width) {
+ for boundary in
+ line_wrapper.wrap_line(&line_fragments, wrap_width, indent_adjustment)
+ {
let wrapped = &line[prev_boundary_ix..boundary.ix];
push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
edit_transforms.push(Transform::wrap(boundary.next_indent));
@@ -886,7 +917,7 @@ impl WrapSnapshot {
let (.., item) = self.transforms.find::<WrapPoint, _>(
(),
&WrapPoint::new(row + WrapRow(1), 0),
- Bias::Right,
+ Bias::Left,
);
item.and_then(|transform| {
if transform.is_isomorphic() {
@@ -1281,6 +1312,15 @@ impl Iterator for WrapRows<'_> {
}
}
+fn indent_adjustment_for(indent: SoftWrapIndent, tab_size: NonZeroU32) -> IndentAdjustment {
+ match indent {
+ SoftWrapIndent::None => IndentAdjustment::NoIndent,
+ SoftWrapIndent::Same => IndentAdjustment::SameIndent,
+ SoftWrapIndent::ExtraOne => IndentAdjustment::ExtraColumns(tab_size.get()),
+ SoftWrapIndent::ExtraTwo => IndentAdjustment::ExtraColumns(tab_size.get() * 2),
+ }
+}
+
impl Transform {
#[ztracing::instrument(skip_all)]
fn isomorphic(summary: TextSummary) -> Self {
@@ -1462,7 +1502,11 @@ mod tests {
use super::*;
use crate::{
MultiBuffer,
- display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
+ display_map::{
+ fold_map::{FoldMap, FoldSnapshot},
+ inlay_map::InlayMap,
+ tab_map::TabMap,
+ },
test::test_font,
};
use futures::stream::StreamExt;
@@ -1473,6 +1517,101 @@ mod tests {
use text::Rope;
use theme::LoadThemes;
+ fn init_wrap_test(
+ text: &str,
+ tab_size: NonZeroU32,
+ soft_wrapping: Option<Pixels>,
+ cx: &mut gpui::TestAppContext,
+ ) -> (Entity<WrapMap>, TabMap, FoldSnapshot) {
+ let text_system = cx.read(|cx| cx.text_system().clone());
+ let font = test_font();
+ let _font_id = text_system.resolve_font(&font);
+ let font_size = px(14.0);
+
+ let buffer = cx.new(|cx| language::Buffer::local(text, cx));
+ let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
+ let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
+ let (_inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
+ let (_fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
+ let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
+ let tabs_snapshot = tab_map.set_max_expansion_column(32);
+ let (wrap_map, _) =
+ cx.update(|cx| WrapMap::new(tabs_snapshot, font, font_size, soft_wrapping, cx));
+ (wrap_map, tab_map, fold_snapshot)
+ }
+
+ #[gpui::test]
+ async fn test_soft_wrap_indent(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let text = "fn main() {\n let some_variable = 1;\n let some_variable = 2;\n}";
+ let (wrap_map, _, _) =
+ init_wrap_test(text, 4.try_into().unwrap(), Some(px(14.0) * 15.0), cx);
+
+ // Test None
+ wrap_map.update(cx, |map, cx| {
+ map.set_soft_wrap_indent(language::language_settings::SoftWrapIndent::None, cx)
+ });
+ let wrap_snapshot = wrap_map.update(cx, |map, _cx| map.snapshot.clone());
+ assert_eq!(
+ wrap_snapshot.text(),
+ "fn main() {\n let some_variable = \n1;\n let some_variable = \n2;\n}"
+ );
+ assert_eq!(wrap_snapshot.soft_wrap_indent(WrapRow(1)), Some(0));
+
+ // Test Same
+ wrap_map.update(cx, |map, cx| {
+ map.set_soft_wrap_indent(language::language_settings::SoftWrapIndent::Same, cx)
+ });
+ let wrap_snapshot = wrap_map.update(cx, |map, _cx| map.snapshot.clone());
+ assert_eq!(
+ wrap_snapshot.text(),
+ "fn main() {\n let some_variable = \n 1;\n let some_variable = \n 2;\n}"
+ );
+
+ // Test ExtraOne
+ wrap_map.update(cx, |map, cx| {
+ map.set_soft_wrap_indent(language::language_settings::SoftWrapIndent::ExtraOne, cx)
+ });
+ let wrap_snapshot = wrap_map.update(cx, |map, _cx| map.snapshot.clone());
+ assert_eq!(
+ wrap_snapshot.text(),
+ "fn main() {\n let some_variable = \n 1;\n let some_variable = \n 2;\n}"
+ );
+
+ // Test ExtraTwo
+ wrap_map.update(cx, |map, cx| {
+ map.set_soft_wrap_indent(language::language_settings::SoftWrapIndent::ExtraTwo, cx)
+ });
+ let wrap_snapshot = wrap_map.update(cx, |map, _cx| map.snapshot.clone());
+ assert_eq!(
+ wrap_snapshot.text(),
+ "fn main() {\n let some_variable = \n 1;\n let some_variable = \n 2;\n}"
+ );
+ }
+
+ #[gpui::test]
+ async fn test_soft_wrap_indent_updates_on_tab_size_change(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let text = " let x = 1;\n";
+ let (wrap_map, mut tab_map, fold_snapshot) =
+ init_wrap_test(text, 4.try_into().unwrap(), Some(px(14.0) * 8.0), cx);
+
+ wrap_map.update(cx, |map, cx| {
+ map.set_soft_wrap_indent(language::language_settings::SoftWrapIndent::ExtraOne, cx)
+ });
+ let wrap_snapshot = wrap_map.update(cx, |map, _cx| map.snapshot.clone());
+ assert_eq!(wrap_snapshot.text(), " let x = \n 1;\n");
+
+ // Change tab_size to 2
+ let (tabs_snapshot, tab_edits) =
+ tab_map.sync(fold_snapshot, Vec::new(), 2.try_into().unwrap());
+ let (wrap_snapshot, _) =
+ wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
+ assert_eq!(wrap_snapshot.text(), " let x = \n 1;\n");
+ }
+
#[gpui::test]
async fn test_prev_row_boundary(cx: &mut gpui::TestAppContext) {
init_test(cx);
@@ -1694,7 +1833,13 @@ mod tests {
log::info!("TabMap text: {:?}", tabs_snapshot.text());
let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
- let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
+ let mut indent_adjustment = IndentAdjustment::default();
+ let expected_text = wrap_text(
+ &tabs_snapshot,
+ wrap_width,
+ indent_adjustment,
+ &mut line_wrapper,
+ );
let (wrap_map, _) =
cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
@@ -1731,8 +1876,22 @@ mod tests {
} else {
Some(px(rng.random_range(0.0..=1000.0)))
};
- log::info!("Setting wrap width to {:?}", wrap_width);
- wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
+ let soft_wrap_indent = match rng.random_range(0..=3) {
+ 0 => SoftWrapIndent::None,
+ 1 => SoftWrapIndent::Same,
+ 2 => SoftWrapIndent::ExtraOne,
+ _ => SoftWrapIndent::ExtraTwo,
+ };
+ indent_adjustment = indent_adjustment_for(soft_wrap_indent, tab_size);
+ log::info!(
+ "Setting wrap width to {:?}, indent to {:?}",
+ wrap_width,
+ soft_wrap_indent
+ );
+ wrap_map.update(cx, |map, cx| {
+ map.set_wrap_width(wrap_width, cx);
+ map.set_soft_wrap_indent(soft_wrap_indent, cx);
+ });
}
20..=39 => {
for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
@@ -1777,7 +1936,12 @@ mod tests {
let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
log::info!("TabMap text: {:?}", tabs_snapshot.text());
- let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
+ let expected_text = wrap_text(
+ &tabs_snapshot,
+ wrap_width,
+ indent_adjustment,
+ &mut line_wrapper,
+ );
let (mut snapshot, wrap_edits) =
wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
snapshot.check_invariants();
@@ -1894,6 +2058,7 @@ mod tests {
fn wrap_text(
tab_snapshot: &TabSnapshot,
wrap_width: Option<Pixels>,
+ indent_adjustment: IndentAdjustment,
line_wrapper: &mut LineWrapper,
) -> String {
if let Some(wrap_width) = wrap_width {
@@ -1904,7 +2069,11 @@ mod tests {
}
let mut prev_ix = 0;
- for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
+ for boundary in line_wrapper.wrap_line(
+ &[LineFragment::text(line)],
+ wrap_width,
+ indent_adjustment,
+ ) {
wrapped_text.push_str(&line[prev_ix..boundary.ix]);
wrapped_text.push('\n');
wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index a26cf4a88d7..bff66cb0f8b 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -189,7 +189,7 @@ use language::{
LocalFile, OffsetRangeExt, OutlineItem, Point, Selection, SelectionGoal, TextObject,
TransactionId, TreeSitterOptions, WordsQuery,
language_settings::{
- self, AllLanguageSettings, LanguageSettings, LspInsertMode, RewrapBehavior,
+ self, AllLanguageSettings, LanguageSettings, LspInsertMode, RewrapBehavior, SoftWrapIndent,
WordsCompletionMode, all_language_settings,
},
point_to_lsp, text_diff_with_options,
@@ -12168,6 +12168,135 @@ impl EditorSnapshot {
.language_at(position)
}
+ pub fn display_row_for_inline_code_action(&self, buffer_point: Point) -> Option<DisplayRow> {
+ if self.is_line_folded(MultiBufferRow(buffer_point.row)) {
+ return None;
+ }
+
+ let line_indent = self
+ .display_snapshot
+ .buffer_snapshot()
+ .line_indent_for_row(MultiBufferRow(buffer_point.row));
+ if line_indent.is_line_blank() {
+ return None;
+ }
+
+ const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
+ const MAX_ALTERNATE_DISTANCE: u32 = 8;
+
+ let is_valid_row = |row_candidate: u32| -> bool {
+ if self.is_line_folded(MultiBufferRow(row_candidate)) {
+ return false;
+ }
+ if buffer_point.row == row_candidate {
+ if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
+ return false;
+ }
+ } else {
+ let candidate_point = MultiBufferPoint {
+ row: row_candidate,
+ column: 0,
+ };
+ let range = if candidate_point < buffer_point {
+ candidate_point..buffer_point
+ } else {
+ buffer_point..candidate_point
+ };
+ if self
+ .display_snapshot
+ .buffer_snapshot()
+ .excerpt_containing(range)
+ .is_none()
+ {
+ return false;
+ }
+ }
+ let line_indent = self
+ .display_snapshot
+ .buffer_snapshot()
+ .line_indent_for_row(MultiBufferRow(row_candidate));
+ if line_indent.is_line_blank() {
+ true
+ } else {
+ let indent_size = self
+ .display_snapshot
+ .buffer_snapshot()
+ .indent_size_for_line(MultiBufferRow(row_candidate));
+ if indent_size.len >= INLINE_SLOT_CHAR_LIMIT {
+ true
+ } else if row_candidate == buffer_point.row {
+ let display_row = self
+ .display_snapshot
+ .point_to_display_point(buffer_point, text::Bias::Left)
+ .row();
+ let line_start_display_row = self
+ .display_snapshot
+ .point_to_display_point(Point::new(buffer_point.row, 0), text::Bias::Left)
+ .row();
+ if display_row > line_start_display_row {
+ self.display_snapshot
+ .soft_wrap_indent(DisplayRow(display_row.0 - 1))
+ .is_some_and(|indent| indent >= INLINE_SLOT_CHAR_LIMIT)
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ }
+ };
+
+ let new_buffer_row = if is_valid_row(buffer_point.row) {
+ Some(buffer_point.row)
+ } else {
+ let max_row = self.display_snapshot.buffer_snapshot().max_point().row;
+ (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
+ let row_above = buffer_point.row.saturating_sub(offset);
+ let row_below = buffer_point.row + offset;
+ if row_above != buffer_point.row && is_valid_row(row_above) {
+ Some(row_above)
+ } else if row_below <= max_row && is_valid_row(row_below) {
+ Some(row_below)
+ } else {
+ None
+ }
+ })
+ }?;
+
+ let mut new_display_row = self
+ .display_snapshot
+ .point_to_display_point(
+ Point {
+ row: new_buffer_row,
+ column: buffer_point.column,
+ },
+ text::Bias::Left,
+ )
+ .row();
+
+ let line_start_display_row = self
+ .display_snapshot
+ .point_to_display_point(
+ Point {
+ row: new_buffer_row,
+ column: 0,
+ },
+ text::Bias::Left,
+ )
+ .row();
+
+ if new_display_row > line_start_display_row
+ && self
+ .display_snapshot
+ .soft_wrap_indent(DisplayRow(new_display_row.0 - 1))
+ .is_some_and(|indent| indent < INLINE_SLOT_CHAR_LIMIT)
+ {
+ new_display_row = line_start_display_row;
+ }
+
+ Some(new_display_row)
+ }
+
pub fn is_focused(&self) -> bool {
self.is_focused
}
diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs
index 4b57c52760e..917a70e5ab0 100644
--- a/crates/editor/src/editor_tests.rs
+++ b/crates/editor/src/editor_tests.rs
@@ -49850,3 +49850,360 @@ fn multiline_add_selection_history_states() -> [(bool, &'static str, &'static st
),
]
}
+
+#[gpui::test]
+async fn test_display_row_for_inline_code_action(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ update_test_language_settings(cx, &|settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.soft_wrap_indent =
+ Some(language::language_settings::SoftWrapIndent::None);
+ settings.defaults.preferred_line_length = Some(25);
+ });
+
+ // 20 spaces indent, then "123456789"
+ let text = " 123456789";
+ let editor = cx.add_window(|window, cx| {
+ build_editor(
+ multi_buffer::MultiBuffer::build_simple(text, cx),
+ window,
+ cx,
+ )
+ });
+
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+
+ // The text wraps after 25 columns.
+ // Indent is 20, plus "12345" is 25. So it wraps before "6789".
+ // Buffer point at column 26 (the '7').
+ let buffer_point = Point::new(0, 26);
+
+ let display_row = snapshot.display_row_for_inline_code_action(buffer_point);
+
+ // With SoftWrapIndent::None, the wrapped line has 0 indent (0 < 4),
+ // so it should snap back to the start of the physical line (DisplayRow 0).
+ assert_eq!(display_row, Some(DisplayRow(0)));
+
+ // Change to SoftWrapIndent::Same, which maintains the 20-space indent
+ update_test_language_settings(cx, &|settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.soft_wrap_indent =
+ Some(language::language_settings::SoftWrapIndent::Same);
+ settings.defaults.preferred_line_length = Some(25);
+ });
+
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+
+ let display_row = snapshot.display_row_for_inline_code_action(buffer_point);
+
+ // With SoftWrapIndent::Same, there is enough space in the gutter,
+ // so it should render on the wrapped display row (DisplayRow 1).
+ assert_eq!(display_row, Some(DisplayRow(1)));
+
+ // 2 spaces of indent at column 0 (< 4), but ExtraTwo wrap adds extra indent (2 + 4 = 6 >= 4) on wrapped line
+ update_test_language_settings(cx, &|settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.soft_wrap_indent =
+ Some(language::language_settings::SoftWrapIndent::ExtraTwo);
+ settings.defaults.tab_size = std::num::NonZeroU32::new(2);
+ settings.defaults.preferred_line_length = Some(25);
+ });
+
+ let text_with_2_spaces = " 12345678901234567890123456789\n123456789";
+ let editor = cx.add_window(|window, cx| {
+ build_editor(
+ multi_buffer::MultiBuffer::build_simple(text_with_2_spaces, cx),
+ window,
+ cx,
+ )
+ });
+
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+
+ let buffer_point = Point::new(0, 26);
+ let display_row = snapshot.display_row_for_inline_code_action(buffer_point);
+
+ // Physical line 0 has 2 spaces indent (< 4), but wrapped DisplayRow(1) has 6 spaces (>= 4).
+ // The code action helper should stay on physical line 0 and render on DisplayRow(1).
+ assert_eq!(display_row, Some(DisplayRow(1)));
+}
+
+#[gpui::test]
+async fn test_display_row_for_inline_code_action_with_block_above(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ update_test_language_settings(cx, &|settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.soft_wrap_indent =
+ Some(language::language_settings::SoftWrapIndent::ExtraOne);
+ settings.defaults.preferred_line_length = Some(25);
+ });
+
+ let text = "1234567890123456789012345678";
+ let editor = cx.add_window(|window, cx| {
+ build_editor(
+ multi_buffer::MultiBuffer::build_simple(text, cx),
+ window,
+ cx,
+ )
+ });
+
+ _ = editor.update(cx, |editor, _window, cx| {
+ let buffer_snapshot = editor.buffer.read(cx).snapshot(cx);
+ editor.insert_blocks(
+ [BlockProperties {
+ style: BlockStyle::Fixed,
+ placement: BlockPlacement::Above(buffer_snapshot.anchor_before(Point::new(0, 0))),
+ height: Some(1),
+ render: Arc::new(|_| div().into_any()),
+ priority: 0,
+ }],
+ None,
+ cx,
+ );
+ });
+
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+
+ // DisplayRow 0 is the block, DisplayRow 1 is the first text row.
+ // The text wraps at column 25 with ExtraOne (4 spaces continuation).
+ // Cursor at column 5 is on the first text row (DisplayRow 1), not a
+ // continuation. The line has 0 indent (< 4) and the cursor is not on a
+ // wrapped continuation, so no valid row exists in this single-line buffer.
+ assert_eq!(
+ snapshot.display_row_for_inline_code_action(Point::new(0, 5)),
+ None
+ );
+
+ // Cursor at column 26 is on the soft-wrapped continuation row (DisplayRow 2).
+ // It has 4 spaces of continuation indent (>= 4), so the code action is placed here.
+ assert_eq!(
+ snapshot.display_row_for_inline_code_action(Point::new(0, 26)),
+ Some(DisplayRow(2))
+ );
+}
+
+#[gpui::test]
+async fn test_soft_wrap_indent_updated_on_language_changed(cx: &mut gpui::TestAppContext) {
+ // Configure Rust to have a different continuation indent behavior than the default.
+ init_test(cx, |settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.soft_wrap_indent =
+ Some(language::language_settings::SoftWrapIndent::Same);
+ settings.defaults.preferred_line_length = Some(20);
+ settings.languages.0.insert(
+ "Rust".into(),
+ LanguageSettingsContent {
+ soft_wrap_indent: Some(language::language_settings::SoftWrapIndent::None),
+ ..Default::default()
+ },
+ );
+ });
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state("ˇ let a_long_variable = 123456789;\n");
+
+ cx.update_editor(|editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::Same
+ );
+ let snapshot = editor.display_snapshot(cx);
+ assert_eq!(snapshot.soft_wrap_indent(DisplayRow(0)), Some(4));
+ });
+
+ cx.update_buffer(|buffer, cx| {
+ buffer.set_language(Some(rust_lang()), cx);
+ });
+
+ cx.update_editor(|editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::None
+ );
+ let snapshot = editor.display_snapshot(cx);
+ assert_eq!(snapshot.soft_wrap_indent(DisplayRow(0)), Some(0));
+ });
+}
+
+#[gpui::test]
+async fn test_soft_wrap_indent_updated_when_first_excerpt_changes(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.soft_wrap_indent =
+ Some(language::language_settings::SoftWrapIndent::Same);
+ settings.defaults.preferred_line_length = Some(20);
+ settings.languages.0.insert(
+ "Rust".into(),
+ LanguageSettingsContent {
+ soft_wrap_indent: Some(language::language_settings::SoftWrapIndent::None),
+ ..Default::default()
+ },
+ );
+ });
+
+ let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadWrite));
+ let editor = cx.add_window(|window, cx| build_editor(multibuffer.clone(), window, cx));
+
+ // Initially empty multibuffer uses global defaults (Same)
+ editor
+ .update(cx, |editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::Same
+ );
+ })
+ .unwrap();
+
+ let buffer = cx.new(|cx| {
+ language::Buffer::local(" let a_long_variable = 123456789;\n", cx)
+ .with_language(rust_lang(), cx)
+ });
+ let (buffer_id, max_point) =
+ buffer.read_with(cx, |buffer, _cx| (buffer.remote_id(), buffer.max_point()));
+
+ multibuffer.update(cx, |mb, cx| {
+ mb.set_excerpts_for_buffer(buffer, [Point::new(0, 0)..max_point], 0, cx);
+ });
+
+ // Adding the Rust excerpt should update the editor's soft_wrap_indent to None
+ editor
+ .update(cx, |editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::None
+ );
+ })
+ .unwrap();
+
+ // Continuation line has 0 indent instead of inheriting the 4 spaces from the start of the line
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+ assert_eq!(snapshot.soft_wrap_indent(DisplayRow(0)), Some(0));
+
+ // Removing the excerpt returns the editor to global defaults (Same)
+ multibuffer.update(cx, |mb, cx| {
+ mb.remove_excerpts_for_buffer(buffer_id, cx);
+ });
+
+ editor
+ .update(cx, |editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::Same
+ );
+ })
+ .unwrap();
+}
+
+#[gpui::test]
+async fn test_soft_wrap_indent_updated_on_file_move_between_directories(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx, |settings| {
+ settings.defaults.soft_wrap = Some(language::language_settings::SoftWrap::Bounded);
+ settings.defaults.preferred_line_length = Some(20);
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ let root = Path::new("/root");
+ fs.insert_tree(
+ root,
+ serde_json::json!({
+ "dir_a": {
+ ".zed": {
+ "settings.json": "{\n \"soft_wrap_indent\": \"same\"\n}"
+ },
+ "test.txt": " let a_long_variable = 123456789;\n"
+ },
+ "dir_b": {
+ ".zed": {
+ "settings.json": "{\n \"soft_wrap_indent\": \"none\"\n}"
+ }
+ }
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [root], cx).await;
+ let worktree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
+ let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
+
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_buffer((worktree_id, rel_path("dir_a/test.txt")), cx)
+ })
+ .await
+ .unwrap();
+
+ let editor = cx.add_window(|window, cx| {
+ build_editor_with_project(
+ project.clone(),
+ MultiBuffer::build_from_buffer(buffer, cx),
+ window,
+ cx,
+ )
+ });
+
+ cx.run_until_parked();
+
+ // In dir_a, soft_wrap_indent is "same", so continuation row has 4 spaces indent
+ editor
+ .update(cx, |editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::Same
+ );
+ })
+ .unwrap();
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+ assert_eq!(snapshot.soft_wrap_indent(DisplayRow(0)), Some(4));
+
+ // Move test.txt from dir_a to dir_b
+ let entry_id = project
+ .read_with(cx, |project, cx| {
+ project
+ .entry_for_path(&(worktree_id, rel_path("dir_a/test.txt")).into(), cx)
+ .map(|e| e.id)
+ })
+ .unwrap();
+
+ project
+ .update(cx, |project, cx| {
+ project.rename_entry(
+ entry_id,
+ (worktree_id, rel_path("dir_b/test.txt")).into(),
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+
+ cx.run_until_parked();
+
+ // After moving to dir_b, soft_wrap_indent should update to "none"
+ editor
+ .update(cx, |editor, _window, cx| {
+ assert_eq!(
+ editor.soft_wrap_indent(cx),
+ language::language_settings::SoftWrapIndent::None
+ );
+ })
+ .unwrap();
+ let snapshot = editor
+ .update(cx, |editor, window, cx| editor.snapshot(window, cx))
+ .unwrap();
+ assert_eq!(snapshot.soft_wrap_indent(DisplayRow(0)), Some(0));
+}
diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs
index 4e96f08d17c..91f06b0e2ff 100644
--- a/crates/editor/src/element.rs
+++ b/crates/editor/src/element.rs
@@ -2094,98 +2094,7 @@ impl EditorElement {
})?;
let buffer_point = display_point.to_point(&snapshot.display_snapshot);
-
- // do not show code action for folded line
- if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
- return None;
- }
-
- // do not show code action for blank line with cursor
- let line_indent = snapshot
- .display_snapshot
- .buffer_snapshot()
- .line_indent_for_row(MultiBufferRow(buffer_point.row));
- if line_indent.is_line_blank() {
- return None;
- }
-
- const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
- const MAX_ALTERNATE_DISTANCE: u32 = 8;
-
- let is_valid_row = |row_candidate: u32| -> bool {
- // move to other row if folded row
- if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
- return false;
- }
- if buffer_point.row == row_candidate {
- // move to other row if cursor is in slot
- if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
- return false;
- }
- } else {
- let candidate_point = MultiBufferPoint {
- row: row_candidate,
- column: 0,
- };
- // move to other row if different excerpt
- let range = if candidate_point < buffer_point {
- candidate_point..buffer_point
- } else {
- buffer_point..candidate_point
- };
- if snapshot
- .display_snapshot
- .buffer_snapshot()
- .excerpt_containing(range)
- .is_none()
- {
- return false;
- }
- }
- let line_indent = snapshot
- .display_snapshot
- .buffer_snapshot()
- .line_indent_for_row(MultiBufferRow(row_candidate));
- // use this row if it's blank
- if line_indent.is_line_blank() {
- true
- } else {
- // use this row if code starts after slot
- let indent_size = snapshot
- .display_snapshot
- .buffer_snapshot()
- .indent_size_for_line(MultiBufferRow(row_candidate));
- indent_size.len >= INLINE_SLOT_CHAR_LIMIT
- }
- };
-
- let new_buffer_row = if is_valid_row(buffer_point.row) {
- Some(buffer_point.row)
- } else {
- let max_row = snapshot.display_snapshot.buffer_snapshot().max_point().row;
- (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
- let row_above = buffer_point.row.saturating_sub(offset);
- let row_below = buffer_point.row + offset;
- if row_above != buffer_point.row && is_valid_row(row_above) {
- Some(row_above)
- } else if row_below <= max_row && is_valid_row(row_below) {
- Some(row_below)
- } else {
- None
- }
- })
- }?;
-
- let new_display_row = snapshot
- .display_snapshot
- .point_to_display_point(
- Point {
- row: new_buffer_row,
- column: buffer_point.column,
- },
- text::Bias::Left,
- )
- .row();
+ let new_display_row = snapshot.display_row_for_inline_code_action(buffer_point)?;
let start_y = content_origin.y
+ (((new_display_row.as_f64() - scroll_position.y) as f32) * line_height)
diff --git a/crates/gpui/src/text_system/line_wrapper.rs b/crates/gpui/src/text_system/line_wrapper.rs
index 678e9e0f185..ca821bbbb43 100644
--- a/crates/gpui/src/text_system/line_wrapper.rs
+++ b/crates/gpui/src/text_system/line_wrapper.rs
@@ -13,6 +13,18 @@ pub enum TruncateFrom {
Middle,
}
+/// Controls how soft-wrapped continuation lines are indented.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum IndentAdjustment {
+ /// No indent - continuation lines start at column 0.
+ NoIndent,
+ /// Match the original line's leading whitespace.
+ #[default]
+ SameIndent,
+ /// Add N extra columns of indent (in space-character widths).
+ ExtraColumns(u32),
+}
+
/// The GPUI line wrapper, used to wrap lines of text to a given width.
pub struct LineWrapper {
text_system: Arc<TextSystem>,
@@ -41,10 +53,11 @@ impl LineWrapper {
&'a mut self,
fragments: &'a [LineFragment],
wrap_width: Pixels,
+ indent_adjustment: IndentAdjustment,
) -> impl Iterator<Item = Boundary> + 'a {
let mut width = px(0.);
let mut first_non_whitespace_ix = None;
- let mut indent = None;
+ let mut base_indent = None;
let mut last_candidate_ix = 0;
let mut last_candidate_width = px(0.);
let mut last_wrap_ix = 0;
@@ -105,27 +118,65 @@ impl LineWrapper {
width += item_width;
if width > wrap_width && ix > last_wrap_ix {
- if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
- {
- indent = Some(
- Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
- );
+ let wrap_at_candidate =
+ last_candidate_ix > 0 && width - last_candidate_width <= wrap_width;
+
+ let carried_width = if wrap_at_candidate {
+ width - last_candidate_width
+ } else {
+ item_width
+ };
+
+ // Compute base indentation from the first non-whitespace character on the line
+ // and retain it for all subsequent wrap rows. If the line begins with leading
+ // whitespace that wraps before any non-whitespace character (or is all whitespace),
+ // base_indent remains None so continuation rows within the leading whitespace
+ // do not receive ExtraColumns indentation and degrade into cascading short rows.
+ if base_indent.is_none() {
+ if let Some(first_non_whitespace_ix) = first_non_whitespace_ix {
+ base_indent =
+ Some(Self::MAX_INDENT.min(
+ first_non_whitespace_ix.saturating_sub(last_wrap_ix) as u32,
+ ));
+ }
}
- if last_candidate_ix > 0 {
+ let next_indent = match indent_adjustment {
+ IndentAdjustment::NoIndent => 0,
+ IndentAdjustment::SameIndent => base_indent.unwrap_or(0),
+ IndentAdjustment::ExtraColumns(extra) => {
+ if let Some(base_indent) = base_indent {
+ let candidate = base_indent.saturating_add(extra);
+ let candidate_indent_width =
+ self.width_for_char(' ') * candidate as f32;
+ // Reserve headroom for any carried suffix from an earlier word boundary
+ // (and at least 2 columns for a full-width character) so the continuation
+ // line does not immediately exceed wrap width.
+ let min_headroom =
+ carried_width.max(self.width_for_char(' ') * 2.0);
+ if candidate_indent_width + min_headroom > wrap_width {
+ 0
+ } else {
+ Self::MAX_INDENT.min(candidate)
+ }
+ } else {
+ 0
+ }
+ }
+ };
+
+ if wrap_at_candidate {
last_wrap_ix = last_candidate_ix;
width -= last_candidate_width;
- last_candidate_ix = 0;
} else {
last_wrap_ix = ix;
width = item_width;
}
+ last_candidate_ix = 0;
- if let Some(indent) = indent {
- width += self.width_for_char(' ') * indent as f32;
- }
+ width += self.width_for_char(' ') * next_indent as f32;
- return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
+ return Some(Boundary::new(last_wrap_ix, next_indent));
}
prev_c = new_prev_c;
@@ -721,7 +772,11 @@ mod tests {
assert_eq!(
wrapper
- .wrap_line(&[LineFragment::text("aa bbb cccc ddddd eeee")], px(72.))
+ .wrap_line(
+ &[LineFragment::text("aa bbb cccc ddddd eeee")],
+ px(72.),
+ IndentAdjustment::default()
+ )
.collect::<Vec<_>>(),
&[
Boundary::new(7, 0),
@@ -731,7 +786,11 @@ mod tests {
);
assert_eq!(
wrapper
- .wrap_line(&[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")], px(72.0))
+ .wrap_line(
+ &[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")],
+ px(72.0),
+ IndentAdjustment::default()
+ )
.collect::<Vec<_>>(),
&[
Boundary::new(4, 0),
@@ -741,7 +800,11 @@ mod tests {
);
assert_eq!(
wrapper
- .wrap_line(&[LineFragment::text(" aaaaaaa")], px(72.))
+ .wrap_line(
+ &[LineFragment::text(" aaaaaaa")],
+ px(72.),
+ IndentAdjustment::default()
+ )
.collect::<Vec<_>>(),
&[
Boundary::new(7, 5),
@@ -753,7 +816,8 @@ mod tests {
wrapper
.wrap_line(
&[LineFragment::text(" ")],
- px(72.)
+ px(72.),
+ IndentAdjustment::default()
)
.collect::<Vec<_>>(),
&[
@@ -764,7 +828,11 @@ mod tests {
);
assert_eq!(
wrapper
- .wrap_line(&[LineFragment::text(" aaaaaaaaaaaaaa")], px(72.))
+ .wrap_line(
+ &[LineFragment::text(" aaaaaaaaaaaaaa")],
+ px(72.),
+ IndentAdjustment::default()
+ )
.collect::<Vec<_>>(),
&[
Boundary::new(7, 0),
@@ -782,7 +850,8 @@ mod tests {
LineFragment::text("aa bbb "),
LineFragment::text("cccc ddddd eeee")
],
- px(72.)
+ px(72.),
+ IndentAdjustment::default()
)
.collect::<Vec<_>>(),
&[
@@ -803,7 +872,8 @@ mod tests {
LineFragment::element(px(30.), 1),
LineFragment::text(" cccc")
],
- px(72.)
+ px(72.),
+ IndentAdjustment::default()
)
.collect::<Vec<_>>(),
&[
@@ -821,7 +891,8 @@ mod tests {
LineFragment::element(px(50.), 1),
LineFragment::text(" aaaa bbbb cccc dddd")
],
- px(72.)
+ px(72.),
+ IndentAdjustment::default()
)
.collect::<Vec<_>>(),
&[
@@ -841,7 +912,8 @@ mod tests {
LineFragment::element(px(100.), 1),
LineFragment::text(" more text")
],
- px(72.)
+ px(72.),
+ IndentAdjustment::default()
)
.collect::<Vec<_>>(),
&[
@@ -857,7 +929,8 @@ mod tests {
wrapper
.wrap_line(
&[LineFragment::text("a\u{202F}b\u{00A0}c\u{2011}d e")],
- px(72.0)
+ px(72.0),
+ IndentAdjustment::default()
)
.collect::<Vec<_>>(),
&[Boundary::new(12, 0),], // special chars above take up 3, 2 and 3 bytes, so boundary ends up at 12
@@ -1294,7 +1367,11 @@ mod tests {
// The truncated text, when wrapped, must fit within max_lines lines.
let wrap_count = wrapper
- .wrap_line(&[LineFragment::text(&truncated)], wrap_width)
+ .wrap_line(
+ &[LineFragment::text(&truncated)],
+ wrap_width,
+ IndentAdjustment::default(),
+ )
.count();
assert!(
@@ -1359,7 +1436,11 @@ mod tests {
);
let wrap_count = wrapper
- .wrap_line(&[LineFragment::text(&truncated)], wrap_width)
+ .wrap_line(
+ &[LineFragment::text(&truncated)],
+ wrap_width,
+ IndentAdjustment::default(),
+ )
.count();
assert!(
@@ -1584,4 +1665,257 @@ mod tests {
result
);
}
+
+ #[test]
+ fn test_extra_columns_overflow_guard() {
+ let mut wrapper = build_wrapper();
+ let space_width = wrapper.width_for_char(' ');
+
+ // 6 spaces indent, wrap width 10 columns.
+ let text = " ab cd ef gh";
+ let wrap_width = space_width * 10.0;
+
+ // When base_indent + extra overflows wrap width (6 + 8 + 2 > 10),
+ // indent must fall back to 0 instead of degrading to one character per row.
+ //
+ // Expected wrapped lines (10 columns):
+ // | ab | (row 0: 6 spaces + "ab ", len 9)
+ // |cd ef gh | (row 1: 0 indent + "cd ef gh", len 8)
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(text)],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(8),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(9, 0)]
+ );
+
+ // When base_indent + extra fits within wrap width (6 + 2 + 2 <= 10),
+ // the extra indent is applied and not clamped.
+ //
+ // Expected wrapped lines (10 columns):
+ // | ab | (row 0: 6 spaces + "ab ", len 9)
+ // | cd| (row 1: 8 spaces + "cd", len 10)
+ // | ef| (row 2: 8 spaces + "ef", len 10)
+ // | gh| (row 3: 8 spaces + "gh", len 10)
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(text)],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(2),
+ )
+ .collect::<Vec<_>>(),
+ &[
+ Boundary::new(9, 8),
+ Boundary::new(11, 8),
+ Boundary::new(13, 8),
+ Boundary::new(15, 8),
+ ]
+ );
+
+ // When text contains full-width (two-column) glyphs, reserving headroom for a
+ // two-column character (candidate + 2 > wrap_width) ensures that candidate
+ // indents leaving only 1 column cannot accept the indent and overflow.
+ //
+ // 1 space indent, wrap width 10 columns.
+ // " 🦀🦀🦀🦀🦀🦀🦀🦀" with extra=8 (extra_two with tab_size=4):
+ // candidate = 1 + 8 = 9.
+ // With +2 headroom (9 + 2 > 10), indent falls back to 0.
+ //
+ // Expected wrapped lines (10 columns):
+ // | 🦀🦀🦀🦀 | (row 0: 1 space + 4 two-column glyphs, 9 cols)
+ // |🦀🦀🦀🦀 | (row 1: 0 indent + 4 two-column glyphs, 8 cols)
+ let full_width_text = " 🦀🦀🦀🦀🦀🦀🦀🦀";
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(full_width_text)],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(8),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(17, 0)]
+ );
+
+ // When the carried suffix fits within wrap width alongside extra indent
+ // (1 indent + 9 carried suffix = 10 <= 10), the extra indent is applied.
+ //
+ // Expected wrapped lines (10 columns):
+ // |a | (row 0: "a ", len 2)
+ // | abcdefghi| (row 1: 1 indent + "abcdefghi", len 10)
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text("a abcdefghi")],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(1),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(2, 1)]
+ );
+
+ // When extra indent exceeds wrap width by even 1 column
+ // (2 indent + 9 carried suffix = 11 > 10), indent falls back to 0.
+ //
+ // Expected wrapped lines (10 columns):
+ // |a | (row 0: "a ", len 2)
+ // |abcdefghi | (row 1: 0 indent + "abcdefghi", len 9)
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text("a abcdefghi")],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(2),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(2, 0)]
+ );
+
+ // When text wraps at an earlier word boundary, the carried suffix
+ // must be accounted for so indent + carried_suffix <= wrap_width.
+ //
+ // "a abcdefghij" with wrap_width 10 columns, ExtraColumns(8):
+ // candidate = 0 + 8 = 8.
+ // carried suffix = "abcdefghi" (9 columns).
+ // 8 indent + 9 carried suffix = 17 > 10, so indent falls back to 0.
+ //
+ // Expected wrapped lines (10 columns):
+ // |a | (row 0: "a ", len 2)
+ // |abcdefghij| (row 1: 0 indent + "abcdefghij", len 10)
+ let carried_text = "a abcdefghij";
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(carried_text)],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(8),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(2, 0)]
+ );
+
+ // When a wider inline element is encountered after the first wrap,
+ // the overflow guard must evaluate whether the element fits with the extra indent.
+ // If text continues after the element row and wraps again, subsequent continuation
+ // lines resume the extra indent if their carried content fits.
+ //
+ // "abcdefghijk " followed by an 8-column element and "z 12":
+ // Row 0: "abcdefghij" (len 10)
+ // Row 1: "k " (2 cols) with 8 indent (len 10)
+ // Row 2: element (8 cols) cannot fit with 8 indent (8 + 8 = 16 > 10),
+ // so indent falls back to 0. Element (8 cols) + "z " (2 cols) = len 10.
+ // Row 3: "12" (2 cols) fits with 8 indent (8 + 2 = 10 <= 10).
+ //
+ // Expected wrapped lines (10 columns):
+ // |abcdefghij| (row 0: 10 cols)
+ // | k | (row 1: 8 indent + "k ", len 10)
+ // |[ELEMENT]z| (row 2: 0 indent + [ELEMENT (8)] + "z ", len 10)
+ // | 12| (row 3: 8 indent + "12", len 10)
+ let element_fragments = [
+ LineFragment::text("abcdefghijk "),
+ LineFragment::element(space_width * 8.0, 1),
+ LineFragment::text("z 12"),
+ ];
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &element_fragments,
+ wrap_width,
+ IndentAdjustment::ExtraColumns(8),
+ )
+ .collect::<Vec<_>>(),
+ &[
+ Boundary::new(10, 8),
+ Boundary::new(12, 0),
+ Boundary::new(15, 8),
+ ]
+ );
+
+ // A line of only whitespace wrapping before any non-whitespace character
+ // must not have extra columns added to subsequent rows.
+ let spaces = " "; // 20 spaces
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(spaces)],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(8),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(10, 0)]
+ );
+
+ // When leading whitespace wraps before the first non-whitespace character,
+ // base_indent should reflect the leading whitespace on the row where non-whitespace begins.
+ // 14 spaces followed by "ab cd ef gh", wrap width 10:
+ // Row 0: 10 spaces (len 10) -> wraps at ix 10 with indent 0
+ // Row 1: 4 spaces + "ab cd" (len 9) -> wraps at ix 20
+ // base_indent is 14 - 10 = 4.
+ // With ExtraColumns(2), candidate = 4 + 2 = 6. 6 + 2 (headroom) = 8 <= 10.
+ // Row 2 and subsequent rows get indent 6.
+ let multiline_indent_text = " ab cd ef gh";
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(multiline_indent_text)],
+ wrap_width,
+ IndentAdjustment::ExtraColumns(2),
+ )
+ .collect::<Vec<_>>(),
+ &[
+ Boundary::new(10, 0),
+ Boundary::new(20, 6),
+ Boundary::new(23, 6),
+ ]
+ );
+
+ // When a word boundary precedes an oversized carried suffix that itself
+ // exceeds wrap_width (e.g. text followed by an inline element), wrapping
+ // at the earlier candidate would force the continuation row to immediately
+ // overflow even with 0 indent. The wrapper must reject the candidate and
+ // break before the overflowing item instead.
+ //
+ // "aaaaaaaaaaaaaaaaaaa a" (21 chars: 19 'a's, space, 'a') followed by 10-column element:
+ // Row 0: "aaaaaaaaaa" (10 chars, len 10) -> wraps at ix 10
+ // Row 1: "aaaaaaaa" (8 chars) with 2 indent (len 10) -> wraps at ix 18
+ // Row 2: "a a" (3 chars) with 2 indent (len 5)
+ // candidate boundary at ix 20 (space)
+ // Then element (10 cols): width becomes 5 + 10 = 15 > wrap_width (10).
+ // Candidate would carry 'a' (1 col) + element (10 cols) = 11 cols > 10.
+ // Because carried suffix (11) > wrap_width (10), candidate is rejected.
+ // Wrapper breaks at ix 21 (before element) with indent 0.
+ // Row 3: element (10 cols, len 10)
+ let oversized_suffix_fragments = [
+ LineFragment::text("aaaaaaaaaaaaaaaaaaa a"),
+ LineFragment::element(space_width * 10.0, 1),
+ ];
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &oversized_suffix_fragments,
+ wrap_width,
+ IndentAdjustment::ExtraColumns(2),
+ )
+ .collect::<Vec<_>>(),
+ &[
+ Boundary::new(10, 2),
+ Boundary::new(18, 2),
+ Boundary::new(21, 0),
+ ]
+ );
+
+ assert_eq!(
+ wrapper
+ .wrap_line(
+ &[LineFragment::text(" aaaaaaaa")],
+ space_width * 4.0,
+ IndentAdjustment::ExtraColumns(u32::MAX),
+ )
+ .collect::<Vec<_>>(),
+ &[Boundary::new(4, 0), Boundary::new(8, 0)]
+ );
+ }
}
diff --git a/crates/language/src/language_settings.rs b/crates/language/src/language_settings.rs
index 3cd3eac0216..da69ac707b8 100644
--- a/crates/language/src/language_settings.rs
+++ b/crates/language/src/language_settings.rs
@@ -20,7 +20,7 @@ pub use settings::{
EditPredictionDataCollectionChoice, EditPredictionPromptFormatContent, EditPredictionProvider,
EditPredictionsMode, FormatOnSave, Formatter, FormatterList, InlayHintKind,
LanguageSettingsContent, LineEndingSetting, LspInsertMode, REST_OF_LANGUAGE_SERVERS,
- RewrapBehavior, ShowWhitespaceSetting, SoftWrap, WordsCompletionMode,
+ RewrapBehavior, ShowWhitespaceSetting, SoftWrap, SoftWrapIndent, WordsCompletionMode,
};
use settings::{RegisterSetting, Settings, SettingsLocation, SettingsStore, merge_from::MergeFrom};
use shellexpand;
@@ -65,6 +65,8 @@ pub struct LanguageSettings {
pub hard_tabs: bool,
/// How to soft-wrap long lines of text.
pub soft_wrap: settings::SoftWrap,
+ /// How to indent soft-wrapped continuation lines.
+ pub soft_wrap_indent: settings::SoftWrapIndent,
/// The column at which to soft-wrap lines, for buffers where soft-wrap
/// is enabled.
pub preferred_line_length: u32,
@@ -840,6 +842,7 @@ impl settings::Settings for AllLanguageSettings {
tab_size: settings.tab_size.unwrap(),
hard_tabs: settings.hard_tabs.unwrap(),
soft_wrap: settings.soft_wrap.unwrap(),
+ soft_wrap_indent: settings.soft_wrap_indent.unwrap(),
preferred_line_length: settings.preferred_line_length.unwrap(),
show_wrap_guides: settings.show_wrap_guides.unwrap(),
wrap_guides: settings.wrap_guides.unwrap(),
diff --git a/crates/settings/src/vscode_import.rs b/crates/settings/src/vscode_import.rs
index 0fe5162a148..7248c1ab19c 100644
--- a/crates/settings/src/vscode_import.rs
+++ b/crates/settings/src/vscode_import.rs
@@ -552,6 +552,13 @@ impl VsCodeSettings {
fn default_language_settings_content(&self) -> LanguageSettingsContent {
LanguageSettingsContent {
allow_rewrap: None,
+ soft_wrap_indent: self.read_enum("editor.wrappingIndent", |s| match s {
+ "none" => Some(SoftWrapIndent::None),
+ "same" => Some(SoftWrapIndent::Same),
+ "indent" => Some(SoftWrapIndent::ExtraOne),
+ "deepIndent" => Some(SoftWrapIndent::ExtraTwo),
+ _ => None,
+ }),
always_treat_brackets_as_autoclosed: None,
auto_indent: None,
auto_indent_on_paste: self.read_bool("editor.formatOnPaste"),
@@ -1609,4 +1616,39 @@ mod tests {
Some(" — literal".to_string())
);
}
+
+ fn imported_soft_wrap_indent(content: &str) -> Option<SoftWrapIndent> {
+ VsCodeSettings::from_str(content, VsCodeSettingsSource::VsCode)
+ .unwrap()
+ .settings_content()
+ .project
+ .all_languages
+ .defaults
+ .soft_wrap_indent
+ }
+
+ #[test]
+ fn test_import_wrapping_indent() {
+ assert_eq!(
+ imported_soft_wrap_indent(r#"{ "editor.wrappingIndent": "none" }"#),
+ Some(SoftWrapIndent::None)
+ );
+ assert_eq!(
+ imported_soft_wrap_indent(r#"{ "editor.wrappingIndent": "same" }"#),
+ Some(SoftWrapIndent::Same)
+ );
+ assert_eq!(
+ imported_soft_wrap_indent(r#"{ "editor.wrappingIndent": "indent" }"#),
+ Some(SoftWrapIndent::ExtraOne)
+ );
+ assert_eq!(
+ imported_soft_wrap_indent(r#"{ "editor.wrappingIndent": "deepIndent" }"#),
+ Some(SoftWrapIndent::ExtraTwo)
+ );
+ assert_eq!(
+ imported_soft_wrap_indent(r#"{ "editor.wrappingIndent": "invalid" }"#),
+ None
+ );
+ assert_eq!(imported_soft_wrap_indent("{}"), None);
+ }
}
diff --git a/crates/settings_content/src/language.rs b/crates/settings_content/src/language.rs
index 75ea59f83d6..676a356da46 100644
--- a/crates/settings_content/src/language.rs
+++ b/crates/settings_content/src/language.rs
@@ -526,6 +526,34 @@ impl<'de> Deserialize<'de> for ConfiguredLanguageServer {
}
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ JsonSchema,
+ MergeFrom,
+ strum::EnumString,
+ strum::VariantArray,
+ strum::VariantNames,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum SoftWrapIndent {
+ /// Continuation lines start at column 0.
+ None,
+ /// Continuation lines match the original line's indentation.
+ #[default]
+ Same,
+ /// Continuation lines get 1 extra indent level beyond the original.
+ ExtraOne,
+ /// Continuation lines get 2 extra indent levels beyond the original.
+ ExtraTwo,
+}
+
/// The settings for a particular language.
#[with_fallible_options]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
@@ -544,6 +572,10 @@ pub struct LanguageSettingsContent {
///
/// Default: none
pub soft_wrap: Option<SoftWrap>,
+ /// How to indent soft-wrapped continuation lines.
+ ///
+ /// Default: same
+ pub soft_wrap_indent: Option<SoftWrapIndent>,
/// The column at which to soft-wrap lines, for buffers where soft-wrap
/// is enabled.
///
diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs
index 972d401b68f..2c5b4ef9e87 100644
--- a/crates/settings_ui/src/page_data.rs
+++ b/crates/settings_ui/src/page_data.rs
@@ -9399,7 +9399,7 @@ fn language_settings_data() -> Box<[SettingsPageItem]> {
]
}
- fn wrapping_section() -> [SettingsPageItem; 6] {
+ fn wrapping_section() -> [SettingsPageItem; 7] {
[
SettingsPageItem::SectionHeader("Wrapping"),
SettingsPageItem::SettingItem(SettingItem {
@@ -9422,6 +9422,26 @@ fn language_settings_data() -> Box<[SettingsPageItem]> {
metadata: None,
files: USER | PROJECT,
}),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Soft Wrap Indent",
+ description: "How to indent soft-wrapped lines.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("languages.$(language).soft_wrap_indent"),
+ pick: |settings_content| {
+ language_settings_field(settings_content, |language| {
+ language.soft_wrap_indent.as_ref()
+ })
+ },
+ write: |settings_content, value, _| {
+ language_settings_field_mut(settings_content, value, |language, value| {
+ language.soft_wrap_indent = value;
+ })
+ },
+ }),
+ metadata: None,
+ files: USER | PROJECT,
+ }),
SettingsPageItem::SettingItem(SettingItem {
title: "Show Wrap Guides",
description: "Show wrap guides in the editor.",
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index e139245a569..0ca7504f4d5 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -569,6 +569,7 @@ fn init_renderers(cx: &mut App) {
.add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
.add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
.add_basic_renderer::<settings::SoftWrap>(render_dropdown)
+ .add_basic_renderer::<settings::SoftWrapIndent>(render_dropdown)
.add_basic_renderer::<settings::AutoIndentMode>(render_dropdown)
.add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
.add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
diff --git a/docs/src/reference/all-settings.md b/docs/src/reference/all-settings.md
index 69d8eaa91c5..29d4609ec3c 100644
--- a/docs/src/reference/all-settings.md
+++ b/docs/src/reference/all-settings.md
@@ -3409,6 +3409,7 @@ The following settings can be overridden for each specific language:
- [`show_whitespaces`](#show-whitespaces)
- [`whitespace_map`](#whitespace-map)
- [`soft_wrap`](#soft-wrap)
+- [`soft_wrap_indent`](#soft-wrap-indent)
- [`tab_size`](#tab-size)
- [`use_autoclose`](#use-autoclose)
- [`always_treat_brackets_as_autoclosed`](#always-treat-brackets-as-autoclosed)
@@ -4514,6 +4515,19 @@ Positive integer values
3. `editor_width` to wrap lines that overflow the editor width
4. `bounded` to wrap lines at the minimum of `editor_width` and `preferred_line_length`
+## Soft Wrap Indent
+
+- Description: How to indent soft-wrapped continuation lines.
+- Setting: `soft_wrap_indent`
+- Default: `same`
+
+**Options**
+
+1. `none` to start continuation lines at column 0
+2. `same` to match the original line's indentation
+3. `extra_one` to add 1 extra indent level beyond the original line
+4. `extra_two` to add 2 extra indent levels beyond the original line
+
## Show Wrap Guides
- Description: Whether to show wrap guides (vertical rulers) in the editor. Setting this to true will show a guide at the 'preferred_line_length' value if 'soft_wrap' is set to 'preferred_line_length', and will show any additional guides as specified by the 'wrap_guides' setting.