# Fix FormatSelections to only format selected ranges, not entire document \(\#51593\) · gitcafe/zed

[View on GitCafe](https://git.cafe/gitcafe/zed/commit/b7f166ab409f24116716473849a124859a14dddd)

Repository: [gitcafe/zed](https://git.cafe/gitcafe/zed)

Visibility: public

Requested revision: b7f166ab409f24116716473849a124859a14dddd

Requested commit: b7f166ab409f24116716473849a124859a14dddd

Commit: b7f166ab409f24116716473849a124859a14dddd

Tree: 262a614fb440433f0184e8dc1180f993862c6831

Author: Pratik Karki

Committer: GitHub

## Message

```
Fix FormatSelections to only format selected ranges, not entire document (#51593)

When `editor: format selections` get invoked, the Prettier and external
formatter branches in `format_buffer_locally` ignored the selection
ranges entirely, causing the whole document to be formatted.

- Thread selection ranges as UTF-16 offsets through to Prettier via
`rangeStart/rangeEnd` options in the format request.
- Skip external formatters when ranges are present, since they have no
mechanism for range formatting.
- Create diff edits and apply them for JSON-like languages. For
single-expression languages like JSON, it wasn't respecting the range
commands from Prettier. So, filter the diff edits returned by Prettier
to retain only those overlapping with the user's selection byte ranges,
ensuring changes outside the selection are never applied.

Part of #25796 

Before you mark this PR as ready for review, make sure that you have:
- [x] Added a solid test coverage and/or screenshots from doing manual
testing
- [x] Done a self-review taking into account security and performance
aspects
- [x] Aligned any UI changes with the [UI
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)

Release Notes:

- Fixed FormatSelections to only format selected ranges, not the entire
document where prettier is supported.

Current Behaviour:

[original
behaviour.webm](https://github.com/user-attachments/assets/d5f0cb48-4c3f-44aa-89a9-975f31fce92d)

New Behaviour:

[new
behaviour.webm](https://github.com/user-attachments/assets/41e04b90-f37f-43e1-b8ed-4622684454b1)

---------

Signed-off-by: Pratik Karki <pratik@prertik.com>
```

## Parents

- [bc2d08caa91dcceab4500ac541b22bcfac78e8d7](https://git.cafe/gitcafe/zed/commit/bc2d08caa91dcceab4500ac541b22bcfac78e8d7?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zed/tree/b7f166ab409f24116716473849a124859a14dddd?format=markdown)
