div_inspector.rs

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