1use anyhow::{Result, anyhow};
2use editor::{Bias, CompletionProvider, Editor, EditorEvent, EditorMode, ExcerptId, MultiBuffer};
3use fuzzy::StringMatch;
4use gpui::{
5 AsyncWindowContext, DivInspectorState, Entity, InspectorElementId, IntoElement,
6 StyleRefinement, Task, Window, inspector_reflection::FunctionReflection, styled_reflection,
7};
8use language::language_settings::SoftWrap;
9use language::{
10 Anchor, Buffer, BufferSnapshot, CodeLabel, Diagnostic, DiagnosticEntry, DiagnosticSet,
11 DiagnosticSeverity, LanguageServerId, Point, ToOffset as _, ToPoint as _,
12};
13use project::lsp_store::CompletionDocumentation;
14use project::{Completion, CompletionResponse, CompletionSource, Project, ProjectPath};
15use std::cell::RefCell;
16use std::fmt::Write as _;
17use std::ops::Range;
18use std::path::Path;
19use std::rc::Rc;
20use std::sync::LazyLock;
21use ui::{Label, LabelSize, Tooltip, prelude::*, styled_ext_reflection, v_flex};
22use util::split_str_with_ranges;
23
24/// Path used for unsaved buffer that contains style json. To support the json language server, this
25/// matches the name used in the generated schemas.
26const ZED_INSPECTOR_STYLE_JSON: &str = "/zed-inspector-style.json";
27
28pub(crate) struct DivInspector {
29 state: State,
30 project: Entity<Project>,
31 inspector_id: Option<InspectorElementId>,
32 inspector_state: Option<DivInspectorState>,
33 /// Value of `DivInspectorState.base_style` when initially picked.
34 initial_style: StyleRefinement,
35 /// Portion of `initial_style` that can't be converted to rust code.
36 unconvertible_style: StyleRefinement,
37 /// Edits the user has made to the json buffer: `json_editor - (unconvertible_style + rust_editor)`.
38 json_style_overrides: StyleRefinement,
39 /// Error to display from parsing the json, or if serialization errors somehow occur.
40 json_style_error: Option<SharedString>,
41 /// Currently selected completion.
42 rust_completion: Option<String>,
43 /// Range that will be replaced by the completion if selected.
44 rust_completion_replace_range: Option<Range<Anchor>>,
45}
46
47enum State {
48 Loading,
49 BuffersLoaded {
50 rust_style_buffer: Entity<Buffer>,
51 json_style_buffer: Entity<Buffer>,
52 },
53 Ready {
54 rust_style_buffer: Entity<Buffer>,
55 rust_style_editor: Entity<Editor>,
56 json_style_buffer: Entity<Buffer>,
57 json_style_editor: Entity<Editor>,
58 },
59 LoadError {
60 message: SharedString,
61 },
62}
63
64impl DivInspector {
65 pub fn new(
66 project: Entity<Project>,
67 window: &mut Window,
68 cx: &mut Context<Self>,
69 ) -> DivInspector {
70 // Open the buffers once, so they can then be used for each editor.
71 cx.spawn_in(window, {
72 let languages = project.read(cx).languages().clone();
73 let project = project.clone();
74 async move |this, cx| {
75 // Open the JSON style buffer in the inspector-specific project, so that it runs the
76 // JSON language server.
77 let json_style_buffer =
78 Self::create_buffer_in_project(ZED_INSPECTOR_STYLE_JSON, &project, cx).await;
79
80 // Create Rust style buffer without adding it to the project / buffer_store, so that
81 // Rust Analyzer doesn't get started for it.
82 let rust_language_result = languages.language_for_name("Rust").await;
83 let rust_style_buffer = rust_language_result.and_then(|rust_language| {
84 cx.new(|cx| Buffer::local("", cx).with_language(rust_language, cx))
85 });
86
87 match json_style_buffer.and_then(|json_style_buffer| {
88 rust_style_buffer
89 .map(|rust_style_buffer| (json_style_buffer, rust_style_buffer))
90 }) {
91 Ok((json_style_buffer, rust_style_buffer)) => {
92 this.update_in(cx, |this, window, cx| {
93 this.state = State::BuffersLoaded {
94 json_style_buffer: json_style_buffer,
95 rust_style_buffer: rust_style_buffer,
96 };
97
98 // Initialize editors immediately instead of waiting for
99 // `update_inspected_element`. This avoids continuing to show
100 // "Loading..." until the user moves the mouse to a different element.
101 if let Some(id) = this.inspector_id.take() {
102 let inspector_state =
103 window.with_inspector_state(Some(&id), cx, |state, _window| {
104 state.clone()
105 });
106 if let Some(inspector_state) = inspector_state {
107 this.update_inspected_element(&id, inspector_state, window, cx);
108 cx.notify();
109 }
110 }
111 })
112 .ok();
113 }
114 Err(err) => {
115 this.update(cx, |this, _cx| {
116 this.state = State::LoadError {
117 message: format!(
118 "Failed to create buffers for style editing: {err}"
119 )
120 .into(),
121 };
122 })
123 .ok();
124 }
125 }
126 }
127 })
128 .detach();
129
130 DivInspector {
131 state: State::Loading,
132 project,
133 inspector_id: None,
134 inspector_state: None,
135 initial_style: StyleRefinement::default(),
136 unconvertible_style: StyleRefinement::default(),
137 json_style_overrides: StyleRefinement::default(),
138 rust_completion: None,
139 rust_completion_replace_range: None,
140 json_style_error: None,
141 }
142 }
143
144 pub fn update_inspected_element(
145 &mut self,
146 id: &InspectorElementId,
147 inspector_state: DivInspectorState,
148 window: &mut Window,
149 cx: &mut Context<Self>,
150 ) {
151 let style = (*inspector_state.base_style).clone();
152 self.inspector_state = Some(inspector_state);
153
154 if self.inspector_id.as_ref() == Some(id) {
155 return;
156 }
157
158 self.inspector_id = Some(id.clone());
159 self.initial_style = style.clone();
160
161 let (rust_style_buffer, json_style_buffer) = match &self.state {
162 State::BuffersLoaded {
163 rust_style_buffer,
164 json_style_buffer,
165 }
166 | State::Ready {
167 rust_style_buffer,
168 json_style_buffer,
169 ..
170 } => (rust_style_buffer.clone(), json_style_buffer.clone()),
171 State::Loading | State::LoadError { .. } => return,
172 };
173
174 let json_style_editor = self.create_editor(json_style_buffer.clone(), window, cx);
175 let rust_style_editor = self.create_editor(rust_style_buffer.clone(), window, cx);
176
177 rust_style_editor.update(cx, {
178 let div_inspector = cx.entity();
179 |rust_style_editor, _cx| {
180 rust_style_editor.set_completion_provider(Some(Rc::new(
181 RustStyleCompletionProvider { div_inspector },
182 )));
183 }
184 });
185
186 let rust_style = match self.reset_style_editors(&rust_style_buffer, &json_style_buffer, cx)
187 {
188 Ok(rust_style) => {
189 self.json_style_error = None;
190 rust_style
191 }
192 Err(err) => {
193 self.json_style_error = Some(format!("{err}").into());
194 return;
195 }
196 };
197
198 cx.subscribe_in(&json_style_editor, window, {
199 let id = id.clone();
200 let rust_style_buffer = rust_style_buffer.clone();
201 move |this, editor, event: &EditorEvent, window, cx| match event {
202 EditorEvent::BufferEdited => {
203 let style_json = editor.read(cx).text(cx);
204 match serde_json_lenient::from_str_lenient::<StyleRefinement>(&style_json) {
205 Ok(new_style) => {
206 let (rust_style, _) = this.style_from_rust_buffer_snapshot(
207 &rust_style_buffer.read(cx).snapshot(),
208 );
209
210 let mut unconvertible_plus_rust = this.unconvertible_style.clone();
211 unconvertible_plus_rust.refine(&rust_style);
212
213 // The serialization of `DefiniteLength::Fraction` does not perfectly
214 // roundtrip because with f32, `(x / 100.0 * 100.0) == x` is not always
215 // true (such as for `p_1_3`). This can cause these values to
216 // erroneously appear in `json_style_overrides` since they are not
217 // perfectly equal. Roundtripping before `subtract` fixes this.
218 unconvertible_plus_rust =
219 serde_json::to_string(&unconvertible_plus_rust)
220 .ok()
221 .and_then(|json| {
222 serde_json_lenient::from_str_lenient(&json).ok()
223 })
224 .unwrap_or(unconvertible_plus_rust);
225
226 this.json_style_overrides =
227 new_style.subtract(&unconvertible_plus_rust);
228
229 window.with_inspector_state::<DivInspectorState, _>(
230 Some(&id),
231 cx,
232 |inspector_state, _window| {
233 if let Some(inspector_state) = inspector_state.as_mut() {
234 *inspector_state.base_style = new_style;
235 }
236 },
237 );
238 window.refresh();
239 this.json_style_error = None;
240 }
241 Err(err) => this.json_style_error = Some(err.to_string().into()),
242 }
243 }
244 _ => {}
245 }
246 })
247 .detach();
248
249 cx.subscribe(&rust_style_editor, {
250 let json_style_buffer = json_style_buffer.clone();
251 let rust_style_buffer = rust_style_buffer.clone();
252 move |this, _editor, event: &EditorEvent, cx| match event {
253 EditorEvent::BufferEdited => {
254 this.update_json_style_from_rust(&json_style_buffer, &rust_style_buffer, cx);
255 }
256 _ => {}
257 }
258 })
259 .detach();
260
261 self.unconvertible_style = style.subtract(&rust_style);
262 self.json_style_overrides = StyleRefinement::default();
263 self.state = State::Ready {
264 rust_style_buffer,
265 rust_style_editor,
266 json_style_buffer,
267 json_style_editor,
268 };
269 }
270
271 fn reset_style(&mut self, cx: &mut App) {
272 match &self.state {
273 State::Ready {
274 rust_style_buffer,
275 json_style_buffer,
276 ..
277 } => {
278 if let Err(err) = self.reset_style_editors(
279 &rust_style_buffer.clone(),
280 &json_style_buffer.clone(),
281 cx,
282 ) {
283 self.json_style_error = Some(format!("{err}").into());
284 } else {
285 self.json_style_error = None;
286 }
287 }
288 _ => {}
289 }
290 }
291
292 fn reset_style_editors(
293 &self,
294 rust_style_buffer: &Entity<Buffer>,
295 json_style_buffer: &Entity<Buffer>,
296 cx: &mut App,
297 ) -> Result<StyleRefinement> {
298 let json_text = match serde_json::to_string_pretty(&self.initial_style) {
299 Ok(json_text) => json_text,
300 Err(err) => {
301 return Err(anyhow!("Failed to convert style to JSON: {err}"));
302 }
303 };
304
305 let (rust_code, rust_style) = guess_rust_code_from_style(&self.initial_style);
306 rust_style_buffer.update(cx, |rust_style_buffer, cx| {
307 rust_style_buffer.set_text(rust_code, cx);
308 let snapshot = rust_style_buffer.snapshot();
309 let (_, unrecognized_ranges) = self.style_from_rust_buffer_snapshot(&snapshot);
310 Self::set_rust_buffer_diagnostics(
311 unrecognized_ranges,
312 rust_style_buffer,
313 &snapshot,
314 cx,
315 );
316 });
317 json_style_buffer.update(cx, |json_style_buffer, cx| {
318 json_style_buffer.set_text(json_text, cx);
319 });
320
321 Ok(rust_style)
322 }
323
324 fn handle_rust_completion_selection_change(
325 &mut self,
326 rust_completion: Option<String>,
327 cx: &mut Context<Self>,
328 ) {
329 self.rust_completion = rust_completion;
330 if let State::Ready {
331 rust_style_buffer,
332 json_style_buffer,
333 ..
334 } = &self.state
335 {
336 self.update_json_style_from_rust(
337 &json_style_buffer.clone(),
338 &rust_style_buffer.clone(),
339 cx,
340 );
341 }
342 }
343
344 fn update_json_style_from_rust(
345 &mut self,
346 json_style_buffer: &Entity<Buffer>,
347 rust_style_buffer: &Entity<Buffer>,
348 cx: &mut Context<Self>,
349 ) {
350 let rust_style = rust_style_buffer.update(cx, |rust_style_buffer, cx| {
351 let snapshot = rust_style_buffer.snapshot();
352 let (rust_style, unrecognized_ranges) = self.style_from_rust_buffer_snapshot(&snapshot);
353 Self::set_rust_buffer_diagnostics(
354 unrecognized_ranges,
355 rust_style_buffer,
356 &snapshot,
357 cx,
358 );
359 rust_style
360 });
361
362 // Preserve parts of the json style which do not come from the unconvertible style or rust
363 // style. This way user edits to the json style are preserved when they are not overridden
364 // by the rust style.
365 //
366 // This results in a behavior where user changes to the json style that do overlap with the
367 // rust style will get set to the rust style when the user edits the rust style. It would be
368 // possible to update the rust style when the json style changes, but this is undesirable
369 // as the user may be working on the actual code in the rust style.
370 let mut new_style = self.unconvertible_style.clone();
371 new_style.refine(&self.json_style_overrides);
372 let new_style = new_style.refined(rust_style);
373
374 match serde_json::to_string_pretty(&new_style) {
375 Ok(json) => {
376 json_style_buffer.update(cx, |json_style_buffer, cx| {
377 json_style_buffer.set_text(json, cx);
378 });
379 }
380 Err(err) => {
381 self.json_style_error = Some(err.to_string().into());
382 }
383 }
384 }
385
386 fn style_from_rust_buffer_snapshot(
387 &self,
388 snapshot: &BufferSnapshot,
389 ) -> (StyleRefinement, Vec<Range<Anchor>>) {
390 let method_names = if let Some((completion, completion_range)) = self
391 .rust_completion
392 .as_ref()
393 .zip(self.rust_completion_replace_range.as_ref())
394 {
395 let before_text = snapshot
396 .text_for_range(0..completion_range.start.to_offset(&snapshot))
397 .collect::<String>();
398 let after_text = snapshot
399 .text_for_range(
400 completion_range.end.to_offset(&snapshot)
401 ..snapshot.clip_offset(usize::MAX, Bias::Left),
402 )
403 .collect::<String>();
404 let mut method_names = split_str_with_ranges(&before_text, is_not_identifier_char)
405 .into_iter()
406 .map(|(range, name)| (Some(range), name.to_string()))
407 .collect::<Vec<_>>();
408 method_names.push((None, completion.clone()));
409 method_names.extend(
410 split_str_with_ranges(&after_text, is_not_identifier_char)
411 .into_iter()
412 .map(|(range, name)| (Some(range), name.to_string())),
413 );
414 method_names
415 } else {
416 split_str_with_ranges(&snapshot.text(), is_not_identifier_char)
417 .into_iter()
418 .map(|(range, name)| (Some(range), name.to_string()))
419 .collect::<Vec<_>>()
420 };
421
422 let mut style = StyleRefinement::default();
423 let mut unrecognized_ranges = Vec::new();
424 for (range, name) in method_names {
425 if let Some((_, method)) = STYLE_METHODS.iter().find(|(_, m)| m.name == name) {
426 style = method.invoke(style);
427 } else if let Some(range) = range {
428 unrecognized_ranges
429 .push(snapshot.anchor_before(range.start)..snapshot.anchor_before(range.end));
430 }
431 }
432
433 (style, unrecognized_ranges)
434 }
435
436 fn set_rust_buffer_diagnostics(
437 unrecognized_ranges: Vec<Range<Anchor>>,
438 rust_style_buffer: &mut Buffer,
439 snapshot: &BufferSnapshot,
440 cx: &mut Context<Buffer>,
441 ) {
442 let diagnostic_entries = unrecognized_ranges
443 .into_iter()
444 .enumerate()
445 .map(|(ix, range)| DiagnosticEntry {
446 range,
447 diagnostic: Diagnostic {
448 message: "unrecognized".to_string(),
449 severity: DiagnosticSeverity::WARNING,
450 is_primary: true,
451 group_id: ix,
452 ..Default::default()
453 },
454 });
455 let diagnostics = DiagnosticSet::from_sorted_entries(diagnostic_entries, snapshot);
456 rust_style_buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
457 }
458
459 async fn create_buffer_in_project(
460 path: impl AsRef<Path>,
461 project: &Entity<Project>,
462 cx: &mut AsyncWindowContext,
463 ) -> Result<Entity<Buffer>> {
464 let worktree = project
465 .update(cx, |project, cx| project.create_worktree(path, false, cx))?
466 .await?;
467
468 let project_path = worktree.read_with(cx, |worktree, _cx| ProjectPath {
469 worktree_id: worktree.id(),
470 path: Path::new("").into(),
471 })?;
472
473 let buffer = project
474 .update(cx, |project, cx| project.open_path(project_path, cx))?
475 .await?
476 .1;
477
478 Ok(buffer)
479 }
480
481 fn create_editor(
482 &self,
483 buffer: Entity<Buffer>,
484 window: &mut Window,
485 cx: &mut Context<Self>,
486 ) -> Entity<Editor> {
487 cx.new(|cx| {
488 let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
489 let mut editor = Editor::new(
490 EditorMode::full(),
491 multi_buffer,
492 Some(self.project.clone()),
493 window,
494 cx,
495 );
496 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
497 editor.set_show_line_numbers(false, cx);
498 editor.set_show_code_actions(false, cx);
499 editor.set_show_breakpoints(false, cx);
500 editor.set_show_git_diff_gutter(false, cx);
501 editor.set_show_runnables(false, cx);
502 editor.set_show_edit_predictions(Some(false), 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 is_incomplete: false,
671 }]))
672 }
673
674 fn resolve_completions(
675 &self,
676 _buffer: Entity<Buffer>,
677 _completion_indices: Vec<usize>,
678 _completions: Rc<RefCell<Box<[Completion]>>>,
679 _cx: &mut Context<Editor>,
680 ) -> Task<Result<bool>> {
681 Task::ready(Ok(true))
682 }
683
684 fn is_completion_trigger(
685 &self,
686 buffer: &Entity<language::Buffer>,
687 position: language::Anchor,
688 _: &str,
689 _: bool,
690 cx: &mut Context<Editor>,
691 ) -> bool {
692 completion_replace_range(&buffer.read(cx).snapshot(), &position).is_some()
693 }
694
695 fn selection_changed(&self, mat: Option<&StringMatch>, _window: &mut Window, cx: &mut App) {
696 let div_inspector = self.div_inspector.clone();
697 let rust_completion = mat.as_ref().map(|mat| mat.string.clone());
698 cx.defer(move |cx| {
699 div_inspector.update(cx, |div_inspector, cx| {
700 div_inspector.handle_rust_completion_selection_change(rust_completion, cx);
701 });
702 });
703 }
704
705 fn sort_completions(&self) -> bool {
706 false
707 }
708}
709
710fn completion_replace_range(snapshot: &BufferSnapshot, anchor: &Anchor) -> Option<Range<Anchor>> {
711 let point = anchor.to_point(&snapshot);
712 let offset = point.to_offset(&snapshot);
713 let line_start = Point::new(point.row, 0).to_offset(&snapshot);
714 let line_end = Point::new(point.row, snapshot.line_len(point.row)).to_offset(&snapshot);
715 let mut lines = snapshot.text_for_range(line_start..line_end).lines();
716 let line = lines.next()?;
717
718 let start_in_line = &line[..offset - line_start]
719 .rfind(|c| is_not_identifier_char(c) && c != '.')
720 .map(|ix| ix + 1)
721 .unwrap_or(0);
722 let end_in_line = &line[offset - line_start..]
723 .rfind(|c| is_not_identifier_char(c) && c != '(' && c != ')')
724 .unwrap_or(line_end - line_start);
725
726 if end_in_line > start_in_line {
727 let replace_start = snapshot.anchor_before(line_start + start_in_line);
728 let replace_end = snapshot.anchor_before(line_start + end_in_line);
729 Some(replace_start..replace_end)
730 } else {
731 None
732 }
733}