Add support for format_on_save only changed lines (#49964)

## Summary

Introduces `format_on_save` variants that format only modified lines,
limiting formatting to lines changed since the last commit. This
prevents massive diffs when editing legacy codebases. Aligns with VS
Code's `editor.formatOnSaveMode` naming:

- `"modifications"` — formats only git-diffed lines. Requires source
control; skips formatting if no diff is available.
- `"modifications_if_available"` — formats only git-diffed lines,
falling back to full-file formatting for untracked files, when source
control is unavailable, or when the LSP does not support range
formatting.

Also supports importing equivalent VS Code settings
(`formatOnSaveMode`).

This PR uses the range-based whitespace/newline infrastructure from the
dependency PR above.

## Changes


<details>
<summary><b>New settings, modified ranges computation, VS Code
import</b></summary>

### New settings (`language.rs`, `default.json`, `all-settings.md`)

Two new `FormatOnSave` variants: `Modifications` and
`ModificationsIfAvailable`.

### Modified ranges computation (`items.rs`)

- `compute_format_decision()` — reads `format_on_save` setting across
all buffers, determines whether to use ranged formatting (`Ranges`),
full formatting (`Full`), or skip (`Skip`).
- `compute_modified_ranges()` — extracts modified line ranges from git
diff hunks via `BufferDiffSnapshot`.
- `is_empty_range()` — helper to detect deletion-only hunks that produce
no formatable content.

The `save()` method calls `compute_format_decision()` and dispatches
accordingly.

### Modifications mode in `lsp_store.rs`

- Adds `FormatOnSave::Modifications |
FormatOnSave::ModificationsIfAvailable` to the formatter selection match
arm.
- `ModificationsIfAvailable` falls back to full-file formatting when
ranged formatting produces no results.

### VS Code settings import (`vscode_import.rs`, `settings_store.rs`)

Imports `editor.formatOnSaveMode` mapping:
- `"modifications"` → `FormatOnSave::Modifications`
- `"modificationsIfAvailable"` →
`FormatOnSave::ModificationsIfAvailable`
- `"file"` → `FormatOnSave::On`

</details>

## Tests

- `test_modifications_format_on_save` — basic modifications mode
formatting with dirty buffer
- `test_modifications_format_no_changes` — clean buffer triggers no
formatting
- `test_modifications_format_lsp_no_range_support` — LSP without range
formatting skips entirely for `Modifications`
- `test_modifications_format_lsp_returns_empty_edits` — empty edits
handled gracefully
- `test_modifications_format_multiple_hunks` — two non-adjacent edits
produce two separate range formatting requests

---

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable


Closes #16509
Depends on #53942

Release Notes:

- Added `modifications` and `modifications_if_available` options to
`format_on_save`, which format only git-changed lines instead of the
entire file
- When using modifications mode, `remove_trailing_whitespace_on_save`
and `ensure_final_newline_on_save` are also scoped to changed lines,
preventing unwanted diff jitter in legacy codebases
- Added support for importing VS Code's `editor.formatOnSaveMode`
setting

---------

Co-authored-by: Kirill Bulatov <kirill@zed.dev>
This commit is contained in:
G36maid 2026-07-09 00:53:11 +08:00 committed by GitHub
parent 7dc634124c
commit b9f3396b68
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 1507 additions and 34 deletions

View file

@ -1458,7 +1458,13 @@
// The EditorConfig `end_of_line` property overrides this setting and behaves // The EditorConfig `end_of_line` property overrides this setting and behaves
// like `enforce_lf` or `enforce_crlf`. // like `enforce_lf` or `enforce_crlf`.
"line_ending": "detect", "line_ending": "detect",
// Whether or not to perform a buffer format before saving: [on, off] // Whether or not to perform a buffer format before saving:
// "on" format the whole buffer
// "off" do not format
// "modifications" format only lines with unstaged changes; skips formatting
// when no git diff is available or the language server lacks range formatting
// "modifications_if_available" same, but falls back to formatting the whole
// buffer when range formatting cannot be used
// Keep in mind, if the autosave with delay is enabled, format_on_save will be ignored // Keep in mind, if the autosave with delay is enabled, format_on_save will be ignored
"format_on_save": "off", "format_on_save": "off",
// How to perform a buffer format. This setting can take multiple values: // How to perform a buffer format. This setting can take multiple values:

File diff suppressed because it is too large Load diff

View file

@ -19,12 +19,14 @@ use gpui::{
}; };
use language::{ use language::{
Bias, Buffer, BufferRow, CharKind, CharScopeContext, HighlightedText, LocalFile, PLAIN_TEXT, Bias, Buffer, BufferRow, CharKind, CharScopeContext, HighlightedText, LocalFile, PLAIN_TEXT,
Point, SelectionGoal, proto::serialize_anchor as serialize_text_anchor, Point, SelectionGoal,
language_settings::{FormatOnSave, LanguageSettings},
proto::serialize_anchor as serialize_text_anchor,
}; };
use lsp::DiagnosticSeverity; use lsp::DiagnosticSeverity;
use multi_buffer::{BufferOffset, MultiBufferOffset, PathKey}; use multi_buffer::{BufferOffset, MultiBufferOffset, PathKey};
use project::{ use project::{
File, Project, ProjectItem as _, ProjectPath, lsp_store::FormatTrigger, File, Project, ProjectItem as _, ProjectPath, git_store::GitStore, lsp_store::FormatTrigger,
project_settings::ProjectSettings, search::SearchQuery, project_settings::ProjectSettings, search::SearchQuery,
}; };
use rope::TextSummary; use rope::TextSummary;
@ -39,7 +41,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
}; };
use text::{BufferId, BufferSnapshot, OffsetRangeExt, Selection}; use text::{BufferId, BufferSnapshot, OffsetRangeExt, Selection, ToPoint as _};
use ui::{IconDecorationKind, prelude::*}; use ui::{IconDecorationKind, prelude::*};
use util::{ResultExt, TryFutureExt, paths::PathExt, rel_path::RelPath}; use util::{ResultExt, TryFutureExt, paths::PathExt, rel_path::RelPath};
use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams}; use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams};
@ -974,16 +976,21 @@ impl Item for Editor {
cx.spawn_in(window, async move |this, cx| { cx.spawn_in(window, async move |this, cx| {
if options.format { if options.format {
this.update_in(cx, |editor, window, cx| { let format_task = this.update_in(cx, |editor, window, cx| {
editor.perform_format( let format_target = compute_format_target(
project.clone(), &buffers_to_save,
format_trigger, format_trigger,
FormatTarget::Buffers(buffers_to_save.clone()), editor.buffer(),
window, project.read(cx).git_store(),
cx, cx,
) );
})? format_target.map(|target| {
.await?; editor.perform_format(project.clone(), format_trigger, target, window, cx)
})
})?;
if let Some(format_task) = format_task {
format_task.await?;
}
} }
if !buffers_to_save.is_empty() { if !buffers_to_save.is_empty() {
@ -2267,6 +2274,115 @@ fn chunk_search_range(
})) }))
} }
/// Decides what to format based on the `format_on_save` settings of the saved buffers.
///
/// In the modifications modes, only lines with unstaged changes are formatted.
/// When no git diff is available for a buffer, `modifications` skips formatting while `modifications_if_available`
/// falls back to formatting entire buffers.
/// When a diff is available but empty, nothing is formatted in either mode.
fn compute_format_target(
buffers: &HashSet<Entity<Buffer>>,
trigger: FormatTrigger,
multi_buffer: &Entity<MultiBuffer>,
git_store: &Entity<GitStore>,
cx: &App,
) -> Option<FormatTarget> {
if trigger == FormatTrigger::Manual {
return Some(FormatTarget::Buffers(buffers.clone()));
}
let multi_buffer_snapshot = multi_buffer.read(cx).snapshot(cx);
let git_store = git_store.read(cx);
let mut fall_back_to_full_format = false;
let mut modified_ranges: Vec<Range<Point>> = Vec::new();
for buffer_entity in buffers.iter() {
let buffer = buffer_entity.read(cx);
let settings = LanguageSettings::for_buffer(buffer, cx);
match settings.format_on_save {
FormatOnSave::On | FormatOnSave::Off => {
return Some(FormatTarget::Buffers(buffers.clone()));
}
FormatOnSave::Modifications | FormatOnSave::ModificationsIfAvailable => {}
}
let Some(diff_snapshot) = git_store
.get_unstaged_diff(buffer.remote_id(), cx)
.map(|diff| diff.read(cx).snapshot(cx))
else {
if settings.format_on_save == FormatOnSave::ModificationsIfAvailable {
fall_back_to_full_format = true;
}
continue;
};
let anchor_ranges = compute_modified_ranges(&buffer.snapshot(), &diff_snapshot);
let flat_anchors = anchor_ranges
.iter()
.flat_map(|range| [range.start, range.end])
.collect::<Vec<_>>();
let multi_buffer_anchors =
multi_buffer_snapshot.text_anchors_to_visible_anchors(flat_anchors);
for pair in multi_buffer_anchors.chunks_exact(2) {
let (Some(start), Some(end)) = (&pair[0], &pair[1]) else {
continue;
};
modified_ranges
.push(start.to_point(&multi_buffer_snapshot)..end.to_point(&multi_buffer_snapshot));
}
}
if fall_back_to_full_format {
Some(FormatTarget::Buffers(buffers.clone()))
} else if modified_ranges.is_empty() {
None
} else {
Some(FormatTarget::Ranges(modified_ranges))
}
}
/// Computes the buffer ranges that have unstaged changes, expanded to full lines and
/// with adjacent hunks merged, for use with format-on-save. An empty result means the
/// buffer has no formatable modifications.
fn compute_modified_ranges(
buffer_snapshot: &language::BufferSnapshot,
diff_snapshot: &buffer_diff::BufferDiffSnapshot,
) -> Vec<Range<text::Anchor>> {
let mut merged: Vec<Range<text::Anchor>> = Vec::new();
for hunk in diff_snapshot.hunks(buffer_snapshot) {
let range = hunk.buffer_range;
if range.start.cmp(&range.end, buffer_snapshot).is_eq() {
// Deletion-only hunks produce no buffer content to format.
continue;
}
let start_point = range.start.to_point(buffer_snapshot);
let end_point = range.end.to_point(buffer_snapshot);
let start_row = start_point.row;
let end_row = if end_point.column == 0 && end_point.row > start_point.row {
end_point.row - 1
} else {
end_point.row
};
let line_start = text::Point::new(start_row, 0);
let line_end = text::Point::new(end_row, buffer_snapshot.line_len(end_row));
let expanded =
buffer_snapshot.anchor_before(line_start)..buffer_snapshot.anchor_after(line_end);
if let Some(last) = merged.last_mut() {
let last_end_point = last.end.to_point(buffer_snapshot);
if start_row <= last_end_point.row + 1 {
if expanded.end.to_point(buffer_snapshot) > last_end_point {
last.end = expanded.end;
}
continue;
}
}
merged.push(expanded);
}
merged
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::editor_tests::init_test; use crate::editor_tests::init_test;
@ -2921,4 +3037,124 @@ mod tests {
"Editor::deserialize should not add items to panes as a side effect" "Editor::deserialize should not add items to panes as a side effect"
); );
} }
#[gpui::test]
fn test_compute_modified_ranges_git_diff(cx: &mut gpui::TestAppContext) {
let base_text = "line0\nline1\nline2\nline3\nline4\nline5\nline6\n";
// Modify line1 and line5 to create two non-adjacent hunks.
let buffer_text = "line0\nMOD1\nline2\nline3\nline4\nMOD5\nline6\n";
let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
let diff_snapshot = buffer.update(cx, |buffer, cx| {
let diff = cx.new(|cx| {
buffer_diff::BufferDiff::new_with_base_text(base_text, &buffer.text_snapshot(), cx)
});
diff.read(cx).snapshot(cx)
});
let ranges = buffer.update(cx, |buffer, _cx| {
compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
});
assert_eq!(ranges.len(), 2, "expected 2 non-adjacent ranges");
buffer.update(cx, |buffer, _cx| {
let text_snapshot: &text::BufferSnapshot = buffer;
let r0 = ranges[0].start.to_point(text_snapshot)..ranges[0].end.to_point(text_snapshot);
let r1 = ranges[1].start.to_point(text_snapshot)..ranges[1].end.to_point(text_snapshot);
assert_eq!(r0.start.row, 1, "first hunk should start at row 1");
assert_eq!(r0.end.row, 1, "first hunk should end at row 1");
assert_eq!(r1.start.row, 5, "second hunk should start at row 5");
assert_eq!(r1.end.row, 5, "second hunk should end at row 5");
});
}
#[gpui::test]
fn test_compute_modified_ranges_unchanged_buffer(cx: &mut gpui::TestAppContext) {
let buffer_text = "line0\nline1\nline2\n";
let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
let diff_snapshot = buffer.update(cx, |buffer, cx| {
let diff = cx.new(|cx| {
buffer_diff::BufferDiff::new_with_base_text(
buffer_text,
&buffer.text_snapshot(),
cx,
)
});
diff.read(cx).snapshot(cx)
});
let ranges = buffer.update(cx, |buffer, _cx| {
compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
});
assert_eq!(
ranges,
Vec::new(),
"buffer that matches its diff base should produce no modified ranges"
);
}
#[gpui::test]
fn test_compute_modified_ranges_deletion_only(cx: &mut gpui::TestAppContext) {
let base_text = "line0\nline1\nline2\n";
// Buffer has line1 deleted (pure deletion).
let buffer_text = "line0\nline2\n";
let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
let diff_snapshot = buffer.update(cx, |buffer, cx| {
let diff = cx.new(|cx| {
buffer_diff::BufferDiff::new_with_base_text(base_text, &buffer.text_snapshot(), cx)
});
diff.read(cx).snapshot(cx)
});
// Verify the diff has a deletion hunk.
let hunk_count = buffer.update(cx, |buffer, _cx| {
let text_snapshot: &text::BufferSnapshot = buffer;
diff_snapshot.hunks(text_snapshot).count()
});
assert!(hunk_count > 0, "diff should have hunks");
let ranges = buffer.update(cx, |buffer, _cx| {
compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
});
assert_eq!(
ranges,
Vec::new(),
"deletion-only hunks should be skipped, leaving no ranges"
);
}
#[gpui::test]
fn test_compute_modified_ranges_adjacent_hunks(cx: &mut gpui::TestAppContext) {
let base_text = "line0\nline1\nline2\nline3\nline4\n";
// Modify lines 2 and 3 which are adjacent; they should merge into one range.
let buffer_text = "line0\nline1\nMOD2\nMOD3\nline4\n";
let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
let diff_snapshot = buffer.update(cx, |buffer, cx| {
let diff = cx.new(|cx| {
buffer_diff::BufferDiff::new_with_base_text(base_text, &buffer.text_snapshot(), cx)
});
diff.read(cx).snapshot(cx)
});
let ranges = buffer.update(cx, |buffer, _cx| {
compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
});
assert_eq!(
ranges.len(),
1,
"adjacent hunks (rows 2 and 3) should be merged into one range"
);
buffer.update(cx, |buffer, _cx| {
let text_snapshot: &text::BufferSnapshot = buffer;
let r = ranges[0].start.to_point(text_snapshot)..ranges[0].end.to_point(text_snapshot);
assert_eq!(r.start.row, 2, "merged range should start at row 2");
assert_eq!(r.end.row, 3, "merged range should end at row 3");
});
}
} }

View file

@ -14,9 +14,9 @@ fn remove_formatters_on_save_inner(value: &mut Value, path: &[&str]) -> Result<(
let Some(format_on_save) = obj.get("format_on_save").cloned() else { let Some(format_on_save) = obj.get("format_on_save").cloned() else {
return Ok(()); return Ok(());
}; };
let is_format_on_save_set_to_formatter = format_on_save let is_format_on_save_set_to_formatter = format_on_save.as_str().map_or(true, |s| {
.as_str() s != "on" && s != "off" && s != "modifications" && s != "modifications_if_available"
.map_or(true, |s| s != "on" && s != "off"); });
if !is_format_on_save_set_to_formatter { if !is_format_on_save_set_to_formatter {
return Ok(()); return Ok(());
} }

View file

@ -1733,9 +1733,13 @@ impl LocalLspStore {
let formatters = match (trigger, &settings.format_on_save) { let formatters = match (trigger, &settings.format_on_save) {
(FormatTrigger::Save, FormatOnSave::Off) => &[], (FormatTrigger::Save, FormatOnSave::Off) => &[],
(FormatTrigger::Manual, _) | (FormatTrigger::Save, FormatOnSave::On) => { (FormatTrigger::Manual, _)
settings.formatter.as_ref() | (
} FormatTrigger::Save,
FormatOnSave::On
| FormatOnSave::Modifications
| FormatOnSave::ModificationsIfAvailable,
) => settings.formatter.as_ref(),
}; };
let formatters = code_actions_on_format_formatters let formatters = code_actions_on_format_formatters
@ -1763,6 +1767,7 @@ impl LocalLspStore {
&adapters_and_servers, &adapters_and_servers,
&settings, &settings,
request_timeout, request_timeout,
trigger,
logger, logger,
cx, cx,
) )
@ -1783,6 +1788,7 @@ impl LocalLspStore {
adapters_and_servers: &[(Arc<CachedLspAdapter>, Arc<LanguageServer>)], adapters_and_servers: &[(Arc<CachedLspAdapter>, Arc<LanguageServer>)],
settings: &LanguageSettings, settings: &LanguageSettings,
request_timeout: Duration, request_timeout: Duration,
trigger: FormatTrigger,
logger: zlog::Logger, logger: zlog::Logger,
cx: &mut AsyncApp, cx: &mut AsyncApp,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
@ -1925,23 +1931,22 @@ impl LocalLspStore {
}; };
let Some(language_server) = language_server else { let Some(language_server) = language_server else {
log::debug!( zlog::debug!(
"No language server found to format buffer '{:?}'. Skipping", logger =>
buffer_path_abs.as_path().to_string_lossy() "No language server found to format buffer {buffer_path_abs:?}. Skipping",
); );
return Ok(()); return Ok(());
}; };
zlog::trace!( zlog::trace!(
logger => logger =>
"Formatting buffer '{:?}' using language server '{:?}'", "Formatting buffer {buffer_path_abs:?} using language server {:?}",
buffer_path_abs.as_path().to_string_lossy(),
language_server.name() language_server.name()
); );
let edits = if let Some(ranges) = buffer.ranges.as_ref() { let edits = if let Some(ranges) = buffer.ranges.as_ref() {
zlog::trace!(logger => "formatting ranges"); zlog::trace!(logger => "formatting ranges");
Self::format_ranges_via_lsp( let range_edits = Self::format_ranges_via_lsp(
&lsp_store, &lsp_store,
&buffer.handle, &buffer.handle,
ranges, ranges,
@ -1951,8 +1956,38 @@ impl LocalLspStore {
cx, cx,
) )
.await .await
.context("Failed to format ranges via language server")? .context("Failed to format ranges via language server")?;
.unwrap_or_default()
match range_edits {
Some(edits) => edits,
None => {
if trigger == FormatTrigger::Save
&& settings.format_on_save == FormatOnSave::ModificationsIfAvailable
{
zlog::debug!(
logger =>
"Falling back to full format - LSP does not support range formatting"
);
Self::format_via_lsp(
&lsp_store,
&buffer.handle,
buffer_path_abs,
&language_server,
&settings,
cx,
)
.await
.context("failed to format via language server")?
} else {
zlog::debug!(
logger =>
"Skipping range format - language server {:?} does not support range formatting",
language_server.name()
);
Vec::new()
}
}
}
} else { } else {
zlog::trace!(logger => "formatting full"); zlog::trace!(logger => "formatting full");
Self::format_via_lsp( Self::format_via_lsp(

View file

@ -2461,6 +2461,148 @@ mod tests {
.unindent(), .unindent(),
cx, cx,
); );
// formatOnSave: true with formatOnSaveMode: modificationsIfAvailable
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSave": true, "editor.formatOnSaveMode": "modificationsIfAvailable" }"#
.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
},
"format_on_save": "modifications_if_available"
}
"#
.unindent(),
cx,
);
// formatOnSave: true with formatOnSaveMode: modifications
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSave": true, "editor.formatOnSaveMode": "modifications" }"#
.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
},
"format_on_save": "modifications"
}
"#
.unindent(),
cx,
);
// formatOnSave: true with formatOnSaveMode: file
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSave": true, "editor.formatOnSaveMode": "file" }"#.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
},
"format_on_save": "on"
}
"#
.unindent(),
cx,
);
// formatOnSaveMode is ignored when formatOnSave is disabled, as in VS Code
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSave": false, "editor.formatOnSaveMode": "modifications" }"#
.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
},
"format_on_save": "off"
}
"#
.unindent(),
cx,
);
// formatOnSaveMode alone does nothing, as formatOnSave defaults to false in VS Code
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSaveMode": "modifications" }"#.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
}
}
"#
.unindent(),
cx,
);
// formatOnSaveMode not set, formatOnSave: true
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSave": true }"#.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
},
"format_on_save": "on"
}
"#
.unindent(),
cx,
);
// formatOnSaveMode not set, formatOnSave: false
check_vscode_import(
&mut store,
r#"{
}
"#
.unindent(),
r#"{ "editor.formatOnSave": false }"#.to_owned(),
r#"{
"base_keymap": "VSCode",
"minimap": {
"show": "always"
},
"format_on_save": "off"
}
"#
.unindent(),
cx,
);
} }
#[track_caller] #[track_caller]

View file

@ -554,9 +554,15 @@ impl VsCodeSettings {
extend_comment_on_newline: None, extend_comment_on_newline: None,
extend_list_on_newline: None, extend_list_on_newline: None,
indent_list_on_tab: None, indent_list_on_tab: None,
format_on_save: self.read_bool("editor.guides.formatOnSave").map(|b| { // In VS Code, `editor.formatOnSaveMode` only applies when `editor.formatOnSave` is enabled.
if b { format_on_save: self.read_bool("editor.formatOnSave").map(|enabled| {
FormatOnSave::On if enabled {
self.read_enum("editor.formatOnSaveMode", |s| match s {
"modificationsIfAvailable" => Some(FormatOnSave::ModificationsIfAvailable),
"modifications" => Some(FormatOnSave::Modifications),
_ => None,
})
.unwrap_or(FormatOnSave::On)
} else { } else {
FormatOnSave::Off FormatOnSave::Off
} }

View file

@ -923,12 +923,22 @@ pub struct PrettierSettingsContent {
strum::VariantArray, strum::VariantArray,
strum::VariantNames, strum::VariantNames,
)] )]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "snake_case")]
pub enum FormatOnSave { pub enum FormatOnSave {
/// Files should be formatted on save. /// Files should be formatted on save.
On, On,
/// Files should not be formatted on save. /// Files should not be formatted on save.
Off, Off,
/// Only lines with unstaged changes are formatted on save.
/// Requires source control and LSP range formatting support.
/// If no git diff is available or if the LSP doesn't support
/// range formatting, formatting is skipped.
Modifications,
/// Only lines with unstaged changes are formatted on save.
/// If no git diff is available (e.g., when source control is
/// unavailable) or if the LSP doesn't support range formatting,
/// falls back to formatting the whole file.
ModificationsIfAvailable,
} }
/// Controls how line endings are normalized when a buffer is saved. /// Controls how line endings are normalized when a buffer is saved.

View file

@ -8934,7 +8934,7 @@ fn language_settings_data() -> Box<[SettingsPageItem]> {
SettingsPageItem::SectionHeader("Formatting"), SettingsPageItem::SectionHeader("Formatting"),
SettingsPageItem::SettingItem(SettingItem { SettingsPageItem::SettingItem(SettingItem {
title: "Format On Save", title: "Format On Save",
description: "Whether or not to perform a buffer format before saving.", description: "On: format the whole buffer.\nOff: do not format.\nModifications: format only lines with unstaged changes; skips formatting when a git diff or LSP range formatting is unavailable.\nModifications If Available: same, but falls back to formatting the whole buffer.",
field: Box::new( field: Box::new(
// TODO(settings_ui): this setting should just be a bool // TODO(settings_ui): this setting should just be a bool
SettingField { SettingField {

View file

@ -1905,7 +1905,7 @@ While other options may be changed at a runtime and should be placed under `sett
} }
``` ```
## Format On Save ## Format On Save {#format-on-save}
- Description: Whether or not to perform a buffer format before saving. - Description: Whether or not to perform a buffer format before saving.
- Setting: `format_on_save` - Setting: `format_on_save`
@ -1929,6 +1929,26 @@ While other options may be changed at a runtime and should be placed under `sett
} }
``` ```
3. `modifications`, formats only lines with unstaged changes:
```json [settings]
{
"format_on_save": "modifications"
}
```
This mode requires source control and LSP range formatting support. If no git diff is available or if the LSP doesn't support range formatting, formatting is skipped. This is useful for editing legacy codebases where you want to avoid formatting changes in unrelated code.
4. `modifications_if_available`, formats only modified lines with fallback to full file formatting:
```json [settings]
{
"format_on_save": "modifications_if_available"
}
```
Similar to `modifications`, but behaves like `on` when range formatting cannot be applied: when no git diff is available (e.g., when source control is unavailable) or when the language server does not support range formatting. When a git diff is available but contains no unstaged changes, nothing is formatted.
## Formatter ## Formatter
- Description: How to perform a buffer format. - Description: How to perform a buffer format.
@ -3279,7 +3299,7 @@ Examples:
- Description: - Description:
Preview tabs allow you to open files in preview mode, where they close automatically when you switch to another file unless you explicitly pin them. This is useful for quickly viewing files without cluttering your workspace. Preview tabs display their file names in italics. \ Preview tabs allow you to open files in preview mode, where they close automatically when you switch to another file unless you explicitly pin them. This is useful for quickly viewing files without cluttering your workspace. Preview tabs display their file names in italics. \
There are several ways to convert a preview tab into a regular tab: There are several ways to convert a preview tab into a regular tab:
- Double-clicking on the file - Double-clicking on the file
- Double-clicking on the tab header - Double-clicking on the tab header