1use anyhow::{Result, anyhow};
2use editor::{
3 Bias, CompletionProvider, Editor, EditorEvent, EditorMode, ExcerptId, MinimapVisibility,
4 MultiBuffer,
5};
6use fuzzy::StringMatch;
7use gpui::{
8 AsyncWindowContext, DivInspectorState, Entity, InspectorElementId, IntoElement,
9 StyleRefinement, Task, Window, inspector_reflection::FunctionReflection, styled_reflection,
10};
11use language::language_settings::SoftWrap;
12use language::{
13 Anchor, Buffer, BufferSnapshot, CodeLabel, Diagnostic, DiagnosticEntry, DiagnosticSet,
14 DiagnosticSeverity, LanguageServerId, Point, ToOffset as _, ToPoint as _,
15};
16use project::lsp_store::CompletionDocumentation;
17use project::{
18 Completion, CompletionDisplayOptions, CompletionResponse, CompletionSource, Project,
19 ProjectPath,
20};
21use std::fmt::Write as _;
22use std::ops::Range;
23use std::path::Path;
24use std::rc::Rc;
25use std::sync::LazyLock;
26use ui::{Label, LabelSize, Tooltip, prelude::*, styled_ext_reflection, v_flex};
27use util::split_str_with_ranges;
28
29/// Path used for unsaved buffer that contains style json. To support the json language server, this
30/// matches the name used in the generated schemas.
31const ZED_INSPECTOR_STYLE_JSON: &str = util_macros::path!("/zed-inspector-style.json");
32
33pub(crate) struct DivInspector {
34 state: State,
35 project: Entity<Project>,
36 inspector_id: Option<InspectorElementId>,
37 inspector_state: Option<DivInspectorState>,
38 /// Value of `DivInspectorState.base_style` when initially picked.
39 initial_style: StyleRefinement,
40 /// Portion of `initial_style` that can't be converted to rust code.
41 unconvertible_style: StyleRefinement,
42 /// Edits the user has made to the json buffer: `json_editor - (unconvertible_style + rust_editor)`.
43 json_style_overrides: StyleRefinement,
44 /// Error to display from parsing the json, or if serialization errors somehow occur.
45 json_style_error: Option<SharedString>,
46 /// Currently selected completion.
47 rust_completion: Option<String>,
48 /// Range that will be replaced by the completion if selected.
49 rust_completion_replace_range: Option<Range<Anchor>>,
50}
51
52enum State {
53 Loading,
54 BuffersLoaded {
55 rust_style_buffer: Entity<Buffer>,
56 json_style_buffer: Entity<Buffer>,
57 },
58 Ready {
59 rust_style_buffer: Entity<Buffer>,
60 rust_style_editor: Entity<Editor>,
61 json_style_buffer: Entity<Buffer>,
62 json_style_editor: Entity<Editor>,
63 },
64 LoadError {
65 message: SharedString,
66 },
67}
68
69impl DivInspector {
70 pub fn new(
71 project: Entity<Project>,
72 window: &mut Window,
73 cx: &mut Context<Self>,
74 ) -> DivInspector {
75 // Open the buffers once, so they can then be used for each editor.
76 cx.spawn_in(window, {
77 let languages = project.read(cx).languages().clone();
78 let project = project.clone();
79 async move |this, cx| {
80 // Open the JSON style buffer in the inspector-specific project, so that it runs the
81 // JSON language server.
82 let json_style_buffer =
83 Self::create_buffer_in_project(ZED_INSPECTOR_STYLE_JSON, &project, cx).await;
84
85 // Create Rust style buffer without adding it to the project / buffer_store, so that
86 // Rust Analyzer doesn't get started for it.
87 let rust_language_result = languages.language_for_name("Rust").await;
88 let rust_style_buffer = rust_language_result.and_then(|rust_language| {
89 cx.new(|cx| Buffer::local("", cx).with_language(rust_language, cx))
90 });
91
92 match json_style_buffer.and_then(|json_style_buffer| {
93 rust_style_buffer
94 .map(|rust_style_buffer| (json_style_buffer, rust_style_buffer))
95 }) {
96 Ok((json_style_buffer, rust_style_buffer)) => {
97 this.update_in(cx, |this, window, cx| {
98 this.state = State::BuffersLoaded {
99 json_style_buffer,
100 rust_style_buffer,
101 };
102
103 // Initialize editors immediately instead of waiting for
104 // `update_inspected_element`. This avoids continuing to show
105 // "Loading..." until the user moves the mouse to a different element.
106 if let Some(id) = this.inspector_id.take() {
107 let inspector_state =
108 window.with_inspector_state(Some(&id), cx, |state, _window| {
109 state.clone()
110 });
111 if let Some(inspector_state) = inspector_state {
112 this.update_inspected_element(&id, inspector_state, window, cx);
113 cx.notify();
114 }
115 }
116 })
117 .ok();
118 }
119 Err(err) => {
120 this.update(cx, |this, _cx| {
121 this.state = State::LoadError {
122 message: format!(
123 "Failed to create buffers for style editing: {err}"
124 )
125 .into(),
126 };
127 })
128 .ok();
129 }
130 }
131 }
132 })
133 .detach();
134
135 DivInspector {
136 state: State::Loading,
137 project,
138 inspector_id: None,
139 inspector_state: None,
140 initial_style: StyleRefinement::default(),
141 unconvertible_style: StyleRefinement::default(),
142 json_style_overrides: StyleRefinement::default(),
143 rust_completion: None,
144 rust_completion_replace_range: None,
145 json_style_error: None,
146 }
147 }
148
149 pub fn update_inspected_element(
150 &mut self,
151 id: &InspectorElementId,
152 inspector_state: DivInspectorState,
153 window: &mut Window,
154 cx: &mut Context<Self>,
155 ) {
156 let style = (*inspector_state.base_style).clone();
157 self.inspector_state = Some(inspector_state);
158
159 if self.inspector_id.as_ref() == Some(id) {
160 return;
161 }
162
163 self.inspector_id = Some(id.clone());
164 self.initial_style = style.clone();
165
166 let (rust_style_buffer, json_style_buffer) = match &self.state {
167 State::BuffersLoaded {
168 rust_style_buffer,
169 json_style_buffer,
170 }
171 | State::Ready {
172 rust_style_buffer,
173 json_style_buffer,
174 ..
175 } => (rust_style_buffer.clone(), json_style_buffer.clone()),
176 State::Loading | State::LoadError { .. } => return,
177 };
178
179 let json_style_editor = self.create_editor(json_style_buffer.clone(), window, cx);
180 let rust_style_editor = self.create_editor(rust_style_buffer.clone(), window, cx);
181
182 rust_style_editor.update(cx, {
183 let div_inspector = cx.entity();
184 |rust_style_editor, _cx| {
185 rust_style_editor.set_completion_provider(Some(Rc::new(
186 RustStyleCompletionProvider { div_inspector },
187 )));
188 }
189 });
190
191 let rust_style = match self.reset_style_editors(&rust_style_buffer, &json_style_buffer, cx)
192 {
193 Ok(rust_style) => {
194 self.json_style_error = None;
195 rust_style
196 }
197 Err(err) => {
198 self.json_style_error = Some(format!("{err}").into());
199 return;
200 }
201 };
202
203 cx.subscribe_in(&json_style_editor, window, {
204 let id = id.clone();
205 let rust_style_buffer = rust_style_buffer.clone();
206 move |this, editor, event: &EditorEvent, window, cx| {
207 if event == &EditorEvent::BufferEdited {
208 let style_json = editor.read(cx).text(cx);
209 match serde_json_lenient::from_str_lenient::<StyleRefinement>(&style_json) {
210 Ok(new_style) => {
211 let (rust_style, _) = this.style_from_rust_buffer_snapshot(
212 &rust_style_buffer.read(cx).snapshot(),
213 );
214
215 let mut unconvertible_plus_rust = this.unconvertible_style.clone();
216 unconvertible_plus_rust.refine(&rust_style);
217
218 // The serialization of `DefiniteLength::Fraction` does not perfectly
219 // roundtrip because with f32, `(x / 100.0 * 100.0) == x` is not always
220 // true (such as for `p_1_3`). This can cause these values to
221 // erroneously appear in `json_style_overrides` since they are not
222 // perfectly equal. Roundtripping before `subtract` fixes this.
223 unconvertible_plus_rust =
224 serde_json::to_string(&unconvertible_plus_rust)
225 .ok()
226 .and_then(|json| {
227 serde_json_lenient::from_str_lenient(&json).ok()
228 })
229 .unwrap_or(unconvertible_plus_rust);
230
231 this.json_style_overrides =
232 new_style.subtract(&unconvertible_plus_rust);
233
234 window.with_inspector_state::<DivInspectorState, _>(
235 Some(&id),
236 cx,
237 |inspector_state, _window| {
238 if let Some(inspector_state) = inspector_state.as_mut() {
239 *inspector_state.base_style = new_style;
240 }
241 },
242 );
243 window.refresh();
244 this.json_style_error = None;
245 }
246 Err(err) => this.json_style_error = Some(err.to_string().into()),
247 }
248 }
249 }
250 })
251 .detach();
252
253 cx.subscribe(&rust_style_editor, {
254 let json_style_buffer = json_style_buffer.clone();
255 let rust_style_buffer = rust_style_buffer.clone();
256 move |this, _editor, event: &EditorEvent, cx| {
257 if let EditorEvent::BufferEdited = event {
258 this.update_json_style_from_rust(&json_style_buffer, &rust_style_buffer, cx);
259 }
260 }
261 })
262 .detach();
263
264 self.unconvertible_style = style.subtract(&rust_style);
265 self.json_style_overrides = StyleRefinement::default();
266 self.state = State::Ready {
267 rust_style_buffer,
268 rust_style_editor,
269 json_style_buffer,
270 json_style_editor,
271 };
272 }
273
274 fn reset_style(&mut self, cx: &mut App) {
275 if let State::Ready {
276 rust_style_buffer,
277 json_style_buffer,
278 ..
279 } = &self.state
280 {
281 if let Err(err) =
282 self.reset_style_editors(&rust_style_buffer.clone(), &json_style_buffer.clone(), cx)
283 {
284 self.json_style_error = Some(format!("{err}").into());
285 } else {
286 self.json_style_error = None;
287 }
288 }
289 }
290
291 fn reset_style_editors(
292 &self,
293 rust_style_buffer: &Entity<Buffer>,
294 json_style_buffer: &Entity<Buffer>,
295 cx: &mut App,
296 ) -> Result<StyleRefinement> {
297 let json_text = match serde_json::to_string_pretty(&self.initial_style) {
298 Ok(json_text) => json_text,
299 Err(err) => {
300 return Err(anyhow!("Failed to convert style to JSON: {err}"));
301 }
302 };
303
304 let (rust_code, rust_style) = guess_rust_code_from_style(&self.initial_style);
305 rust_style_buffer.update(cx, |rust_style_buffer, cx| {
306 rust_style_buffer.set_text(rust_code, cx);
307 let snapshot = rust_style_buffer.snapshot();
308 let (_, unrecognized_ranges) = self.style_from_rust_buffer_snapshot(&snapshot);
309 Self::set_rust_buffer_diagnostics(
310 unrecognized_ranges,
311 rust_style_buffer,
312 &snapshot,
313 cx,
314 );
315 });
316 json_style_buffer.update(cx, |json_style_buffer, cx| {
317 json_style_buffer.set_text(json_text, cx);
318 });
319
320 Ok(rust_style)
321 }
322
323 fn handle_rust_completion_selection_change(
324 &mut self,
325 rust_completion: Option<String>,
326 cx: &mut Context<Self>,
327 ) {
328 self.rust_completion = rust_completion;
329 if let State::Ready {
330 rust_style_buffer,
331 json_style_buffer,
332 ..
333 } = &self.state
334 {
335 self.update_json_style_from_rust(
336 &json_style_buffer.clone(),
337 &rust_style_buffer.clone(),
338 cx,
339 );
340 }
341 }
342
343 fn update_json_style_from_rust(
344 &mut self,
345 json_style_buffer: &Entity<Buffer>,
346 rust_style_buffer: &Entity<Buffer>,
347 cx: &mut Context<Self>,
348 ) {
349 let rust_style = rust_style_buffer.update(cx, |rust_style_buffer, cx| {
350 let snapshot = rust_style_buffer.snapshot();
351 let (rust_style, unrecognized_ranges) = self.style_from_rust_buffer_snapshot(&snapshot);
352 Self::set_rust_buffer_diagnostics(
353 unrecognized_ranges,
354 rust_style_buffer,
355 &snapshot,
356 cx,
357 );
358 rust_style
359 });
360
361 // Preserve parts of the json style which do not come from the unconvertible style or rust
362 // style. This way user edits to the json style are preserved when they are not overridden
363 // by the rust style.
364 //
365 // This results in a behavior where user changes to the json style that do overlap with the
366 // rust style will get set to the rust style when the user edits the rust style. It would be
367 // possible to update the rust style when the json style changes, but this is undesirable
368 // as the user may be working on the actual code in the rust style.
369 let mut new_style = self.unconvertible_style.clone();
370 new_style.refine(&self.json_style_overrides);
371 let new_style = new_style.refined(rust_style);
372
373 match serde_json::to_string_pretty(&new_style) {
374 Ok(json) => {
375 json_style_buffer.update(cx, |json_style_buffer, cx| {
376 json_style_buffer.set_text(json, cx);
377 });
378 }
379 Err(err) => {
380 self.json_style_error = Some(err.to_string().into());
381 }
382 }
383 }
384
385 fn style_from_rust_buffer_snapshot(
386 &self,
387 snapshot: &BufferSnapshot,
388 ) -> (StyleRefinement, Vec<Range<Anchor>>) {
389 let method_names = if let Some((completion, completion_range)) = self
390 .rust_completion
391 .as_ref()
392 .zip(self.rust_completion_replace_range.as_ref())
393 {
394 let before_text = snapshot
395 .text_for_range(0..completion_range.start.to_offset(snapshot))
396 .collect::<String>();
397 let after_text = snapshot
398 .text_for_range(
399 completion_range.end.to_offset(snapshot)
400 ..snapshot.clip_offset(usize::MAX, Bias::Left),
401 )
402 .collect::<String>();
403 let mut method_names = split_str_with_ranges(&before_text, is_not_identifier_char)
404 .into_iter()
405 .map(|(range, name)| (Some(range), name.to_string()))
406 .collect::<Vec<_>>();
407 method_names.push((None, completion.clone()));
408 method_names.extend(
409 split_str_with_ranges(&after_text, is_not_identifier_char)
410 .into_iter()
411 .map(|(range, name)| (Some(range), name.to_string())),
412 );
413 method_names
414 } else {
415 split_str_with_ranges(&snapshot.text(), is_not_identifier_char)
416 .into_iter()
417 .map(|(range, name)| (Some(range), name.to_string()))
418 .collect::<Vec<_>>()
419 };
420
421 let mut style = StyleRefinement::default();
422 let mut unrecognized_ranges = Vec::new();
423 for (range, name) in method_names {
424 if let Some((_, method)) = STYLE_METHODS.iter().find(|(_, m)| m.name == name) {
425 style = method.invoke(style);
426 } else if let Some(range) = range {
427 unrecognized_ranges
428 .push(snapshot.anchor_before(range.start)..snapshot.anchor_before(range.end));
429 }
430 }
431
432 (style, unrecognized_ranges)
433 }
434
435 fn set_rust_buffer_diagnostics(
436 unrecognized_ranges: Vec<Range<Anchor>>,
437 rust_style_buffer: &mut Buffer,
438 snapshot: &BufferSnapshot,
439 cx: &mut Context<Buffer>,
440 ) {
441 let diagnostic_entries = unrecognized_ranges
442 .into_iter()
443 .enumerate()
444 .map(|(ix, range)| DiagnosticEntry {
445 range,
446 diagnostic: Diagnostic {
447 message: "unrecognized".to_string(),
448 severity: DiagnosticSeverity::WARNING,
449 is_primary: true,
450 group_id: ix,
451 ..Default::default()
452 },
453 });
454 let diagnostics = DiagnosticSet::from_sorted_entries(diagnostic_entries, snapshot);
455 rust_style_buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
456 }
457
458 async fn create_buffer_in_project(
459 path: impl AsRef<Path>,
460 project: &Entity<Project>,
461 cx: &mut AsyncWindowContext,
462 ) -> Result<Entity<Buffer>> {
463 let worktree = project
464 .update(cx, |project, cx| project.create_worktree(path, false, cx))?
465 .await?;
466
467 let project_path = worktree.read_with(cx, |worktree, _cx| ProjectPath {
468 worktree_id: worktree.id(),
469 path: Path::new("").into(),
470 })?;
471
472 let buffer = project
473 .update(cx, |project, cx| project.open_path(project_path, cx))?
474 .await?
475 .1;
476
477 Ok(buffer)
478 }
479
480 fn create_editor(
481 &self,
482 buffer: Entity<Buffer>,
483 window: &mut Window,
484 cx: &mut Context<Self>,
485 ) -> Entity<Editor> {
486 cx.new(|cx| {
487 let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
488 let mut editor = Editor::new(
489 EditorMode::full(),
490 multi_buffer,
491 Some(self.project.clone()),
492 window,
493 cx,
494 );
495 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
496 editor.set_show_line_numbers(false, cx);
497 editor.set_show_code_actions(false, cx);
498 editor.set_show_breakpoints(false, cx);
499 editor.set_show_git_diff_gutter(false, cx);
500 editor.set_show_runnables(false, cx);
501 editor.set_show_edit_predictions(Some(false), window, cx);
502 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
503 editor
504 })
505 }
506}
507
508impl Render for DivInspector {
509 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
510 v_flex()
511 .size_full()
512 .gap_2()
513 .when_some(self.inspector_state.as_ref(), |this, inspector_state| {
514 this.child(
515 v_flex()
516 .child(Label::new("Layout").size(LabelSize::Large))
517 .child(render_layout_state(inspector_state, cx)),
518 )
519 })
520 .map(|this| match &self.state {
521 State::Loading | State::BuffersLoaded { .. } => {
522 this.child(Label::new("Loading..."))
523 }
524 State::LoadError { message } => this.child(
525 div()
526 .w_full()
527 .border_1()
528 .border_color(Color::Error.color(cx))
529 .child(Label::new(message)),
530 ),
531 State::Ready {
532 rust_style_editor,
533 json_style_editor,
534 ..
535 } => this
536 .child(
537 v_flex()
538 .gap_2()
539 .child(
540 h_flex()
541 .justify_between()
542 .child(Label::new("Rust Style").size(LabelSize::Large))
543 .child(
544 IconButton::new("reset-style", IconName::Eraser)
545 .tooltip(Tooltip::text("Reset style"))
546 .on_click(cx.listener(|this, _, _window, cx| {
547 this.reset_style(cx);
548 })),
549 ),
550 )
551 .child(div().h_64().child(rust_style_editor.clone())),
552 )
553 .child(
554 v_flex()
555 .gap_2()
556 .child(Label::new("JSON Style").size(LabelSize::Large))
557 .child(div().h_128().child(json_style_editor.clone()))
558 .when_some(self.json_style_error.as_ref(), |this, last_error| {
559 this.child(
560 div()
561 .w_full()
562 .border_1()
563 .border_color(Color::Error.color(cx))
564 .child(Label::new(last_error)),
565 )
566 }),
567 ),
568 })
569 .into_any_element()
570 }
571}
572
573fn render_layout_state(inspector_state: &DivInspectorState, cx: &App) -> Div {
574 v_flex()
575 .child(
576 div()
577 .text_ui(cx)
578 .child(format!("Bounds: {}", inspector_state.bounds)),
579 )
580 .child(
581 div()
582 .id("content-size")
583 .text_ui(cx)
584 .tooltip(Tooltip::text("Size of the element's children"))
585 .child(
586 if inspector_state.content_size != inspector_state.bounds.size {
587 format!("Content size: {}", inspector_state.content_size)
588 } else {
589 "".to_string()
590 },
591 ),
592 )
593}
594
595static STYLE_METHODS: LazyLock<Vec<(Box<StyleRefinement>, FunctionReflection<StyleRefinement>)>> =
596 LazyLock::new(|| {
597 // Include StyledExt methods first so that those methods take precedence.
598 styled_ext_reflection::methods::<StyleRefinement>()
599 .into_iter()
600 .chain(styled_reflection::methods::<StyleRefinement>())
601 .map(|method| (Box::new(method.invoke(StyleRefinement::default())), method))
602 .collect()
603 });
604
605fn guess_rust_code_from_style(goal_style: &StyleRefinement) -> (String, StyleRefinement) {
606 let mut subset_methods = Vec::new();
607 for (style, method) in STYLE_METHODS.iter() {
608 if goal_style.is_superset_of(style) {
609 subset_methods.push(method);
610 }
611 }
612
613 let mut code = "fn build() -> Div {\n div()".to_string();
614 let mut style = StyleRefinement::default();
615 for method in subset_methods {
616 let before_change = style.clone();
617 style = method.invoke(style);
618 if before_change != style {
619 let _ = write!(code, "\n .{}()", &method.name);
620 }
621 }
622 code.push_str("\n}");
623
624 (code, style)
625}
626
627fn is_not_identifier_char(c: char) -> bool {
628 !c.is_alphanumeric() && c != '_'
629}
630
631struct RustStyleCompletionProvider {
632 div_inspector: Entity<DivInspector>,
633}
634
635impl CompletionProvider for RustStyleCompletionProvider {
636 fn completions(
637 &self,
638 _excerpt_id: ExcerptId,
639 buffer: &Entity<Buffer>,
640 position: Anchor,
641 _: editor::CompletionContext,
642 _window: &mut Window,
643 cx: &mut Context<Editor>,
644 ) -> Task<Result<Vec<CompletionResponse>>> {
645 let Some(replace_range) = completion_replace_range(&buffer.read(cx).snapshot(), &position)
646 else {
647 return Task::ready(Ok(Vec::new()));
648 };
649
650 self.div_inspector.update(cx, |div_inspector, _cx| {
651 div_inspector.rust_completion_replace_range = Some(replace_range.clone());
652 });
653
654 Task::ready(Ok(vec![CompletionResponse {
655 completions: STYLE_METHODS
656 .iter()
657 .map(|(_, method)| Completion {
658 replace_range: replace_range.clone(),
659 new_text: format!(".{}()", method.name),
660 label: CodeLabel::plain(method.name.to_string(), None),
661 icon_path: None,
662 documentation: method.documentation.map(|documentation| {
663 CompletionDocumentation::MultiLineMarkdown(documentation.into())
664 }),
665 source: CompletionSource::Custom,
666 insert_text_mode: None,
667 confirm: None,
668 })
669 .collect(),
670 display_options: CompletionDisplayOptions::default(),
671 is_incomplete: false,
672 }]))
673 }
674
675 fn is_completion_trigger(
676 &self,
677 buffer: &Entity<language::Buffer>,
678 position: language::Anchor,
679 _text: &str,
680 _trigger_in_words: bool,
681 _menu_is_open: bool,
682 cx: &mut Context<Editor>,
683 ) -> bool {
684 completion_replace_range(&buffer.read(cx).snapshot(), &position).is_some()
685 }
686
687 fn selection_changed(&self, mat: Option<&StringMatch>, _window: &mut Window, cx: &mut App) {
688 let div_inspector = self.div_inspector.clone();
689 let rust_completion = mat.as_ref().map(|mat| mat.string.clone());
690 cx.defer(move |cx| {
691 div_inspector.update(cx, |div_inspector, cx| {
692 div_inspector.handle_rust_completion_selection_change(rust_completion, cx);
693 });
694 });
695 }
696
697 fn sort_completions(&self) -> bool {
698 false
699 }
700}
701
702fn completion_replace_range(snapshot: &BufferSnapshot, anchor: &Anchor) -> Option<Range<Anchor>> {
703 let point = anchor.to_point(snapshot);
704 let offset = point.to_offset(snapshot);
705 let line_start = Point::new(point.row, 0).to_offset(snapshot);
706 let line_end = Point::new(point.row, snapshot.line_len(point.row)).to_offset(snapshot);
707 let mut lines = snapshot.text_for_range(line_start..line_end).lines();
708 let line = lines.next()?;
709
710 let start_in_line = &line[..offset - line_start]
711 .rfind(|c| is_not_identifier_char(c) && c != '.')
712 .map(|ix| ix + 1)
713 .unwrap_or(0);
714 let end_in_line = &line[offset - line_start..]
715 .rfind(|c| is_not_identifier_char(c) && c != '(' && c != ')')
716 .unwrap_or(line_end - line_start);
717
718 if end_in_line > start_in_line {
719 let replace_start = snapshot.anchor_before(line_start + start_in_line);
720 let replace_end = snapshot.anchor_after(line_start + end_in_line);
721 Some(replace_start..replace_end)
722 } else {
723 None
724 }
725}