1use anyhow::{Result, anyhow};
2use editor::{
3 Bias, CompletionProvider, Editor, EditorEvent, EditorMode, MinimapVisibility, MultiBuffer,
4};
5use fuzzy::StringMatch;
6use gpui::{
7 AsyncWindowContext, DivInspectorState, Entity, InspectorElementId, IntoElement,
8 StyleRefinement, Task, Window, inspector_reflection::FunctionReflection, styled_reflection,
9};
10use language::language_settings::SoftWrap;
11use language::{
12 Anchor, Buffer, BufferSnapshot, CodeLabel, Diagnostic, DiagnosticEntry, DiagnosticSet,
13 DiagnosticSeverity, LanguageServerId, Point, ToOffset as _, ToPoint as _,
14};
15use project::lsp_store::CompletionDocumentation;
16use project::{
17 Completion, CompletionDisplayOptions, CompletionResponse, CompletionSource, Project,
18 ProjectPath,
19};
20use std::fmt::Write as _;
21use std::ops::Range;
22use std::path::Path;
23use std::rc::Rc;
24use std::sync::LazyLock;
25use ui::{Label, LabelSize, Tooltip, prelude::*, styled_ext_reflection, v_flex};
26use util::rel_path::RelPath;
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.map(|rust_language| {
89 cx.new(|cx| Buffer::local("", cx).with_language_async(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: RelPath::empty().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.disable_mouse_wheel_zoom();
502 editor.set_show_edit_predictions(Some(false), window, cx);
503 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
504 editor
505 })
506 }
507}
508
509impl Render for DivInspector {
510 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
511 v_flex()
512 .size_full()
513 .gap_2()
514 .when_some(self.inspector_state.as_ref(), |this, inspector_state| {
515 this.child(
516 v_flex()
517 .child(Label::new("Layout").size(LabelSize::Large))
518 .child(render_layout_state(inspector_state, cx)),
519 )
520 })
521 .map(|this| match &self.state {
522 State::Loading | State::BuffersLoaded { .. } => {
523 this.child(Label::new("Loading..."))
524 }
525 State::LoadError { message } => this.child(
526 div()
527 .w_full()
528 .border_1()
529 .border_color(Color::Error.color(cx))
530 .child(Label::new(message)),
531 ),
532 State::Ready {
533 rust_style_editor,
534 json_style_editor,
535 ..
536 } => this
537 .child(
538 v_flex()
539 .gap_2()
540 .child(
541 h_flex()
542 .justify_between()
543 .child(Label::new("Rust Style").size(LabelSize::Large))
544 .child(
545 IconButton::new("reset-style", IconName::Eraser)
546 .tooltip(Tooltip::text("Reset style"))
547 .on_click(cx.listener(|this, _, _window, cx| {
548 this.reset_style(cx);
549 })),
550 ),
551 )
552 .child(div().h_64().child(rust_style_editor.clone())),
553 )
554 .child(
555 v_flex()
556 .gap_2()
557 .child(Label::new("JSON Style").size(LabelSize::Large))
558 .child(div().h_128().child(json_style_editor.clone()))
559 .when_some(self.json_style_error.as_ref(), |this, last_error| {
560 this.child(
561 div()
562 .w_full()
563 .border_1()
564 .border_color(Color::Error.color(cx))
565 .child(Label::new(last_error)),
566 )
567 }),
568 ),
569 })
570 .into_any_element()
571 }
572}
573
574fn render_layout_state(inspector_state: &DivInspectorState, cx: &App) -> Div {
575 v_flex()
576 .child(
577 div()
578 .text_ui(cx)
579 .child(format!(
580 "Bounds: ⌜{} - {}⌟",
581 inspector_state.bounds.origin,
582 inspector_state.bounds.bottom_right()
583 ))
584 .child(format!("Size: {}", inspector_state.bounds.size)),
585 )
586 .child(
587 div()
588 .id("content-size")
589 .text_ui(cx)
590 .tooltip(Tooltip::text("Size of the element's children"))
591 .child(
592 if inspector_state.content_size != inspector_state.bounds.size {
593 format!("Content size: {}", inspector_state.content_size)
594 } else {
595 "".to_string()
596 },
597 ),
598 )
599}
600
601static STYLE_METHODS: LazyLock<Vec<(Box<StyleRefinement>, FunctionReflection<StyleRefinement>)>> =
602 LazyLock::new(|| {
603 // Include StyledExt methods first so that those methods take precedence.
604 styled_ext_reflection::methods::<StyleRefinement>()
605 .into_iter()
606 .chain(styled_reflection::methods::<StyleRefinement>())
607 .map(|method| (Box::new(method.invoke(StyleRefinement::default())), method))
608 .collect()
609 });
610
611fn guess_rust_code_from_style(goal_style: &StyleRefinement) -> (String, StyleRefinement) {
612 let mut subset_methods = Vec::new();
613 for (style, method) in STYLE_METHODS.iter() {
614 if goal_style.is_superset_of(style) {
615 subset_methods.push(method);
616 }
617 }
618
619 let mut code = "fn build() -> Div {\n div()".to_string();
620 let mut style = StyleRefinement::default();
621 for method in subset_methods {
622 let before_change = style.clone();
623 style = method.invoke(style);
624 if before_change != style {
625 let _ = write!(code, "\n .{}()", &method.name);
626 }
627 }
628 code.push_str("\n}");
629
630 (code, style)
631}
632
633fn is_not_identifier_char(c: char) -> bool {
634 !c.is_alphanumeric() && c != '_'
635}
636
637struct RustStyleCompletionProvider {
638 div_inspector: Entity<DivInspector>,
639}
640
641impl CompletionProvider for RustStyleCompletionProvider {
642 fn completions(
643 &self,
644 buffer: &Entity<Buffer>,
645 position: Anchor,
646 _: editor::CompletionContext,
647 _window: &mut Window,
648 cx: &mut Context<Editor>,
649 ) -> Task<Result<Vec<CompletionResponse>>> {
650 let Some(replace_range) = completion_replace_range(&buffer.read(cx).snapshot(), &position)
651 else {
652 return Task::ready(Ok(Vec::new()));
653 };
654
655 self.div_inspector.update(cx, |div_inspector, _cx| {
656 div_inspector.rust_completion_replace_range = Some(replace_range.clone());
657 });
658
659 Task::ready(Ok(vec![CompletionResponse {
660 completions: STYLE_METHODS
661 .iter()
662 .map(|(_, method)| Completion {
663 replace_range: replace_range.clone(),
664 new_text: format!(".{}()", method.name),
665 label: CodeLabel::plain(method.name.to_string(), None),
666 match_start: None,
667 snippet_deduplication_key: None,
668 icon_path: None,
669 documentation: method.documentation.map(|documentation| {
670 CompletionDocumentation::MultiLineMarkdown(documentation.into())
671 }),
672 source: CompletionSource::Custom,
673 insert_text_mode: None,
674 confirm: None,
675 })
676 .collect(),
677 display_options: CompletionDisplayOptions::default(),
678 is_incomplete: false,
679 }]))
680 }
681
682 fn is_completion_trigger(
683 &self,
684 buffer: &Entity<language::Buffer>,
685 position: language::Anchor,
686 _text: &str,
687 _trigger_in_words: bool,
688 cx: &mut Context<Editor>,
689 ) -> bool {
690 completion_replace_range(&buffer.read(cx).snapshot(), &position).is_some()
691 }
692
693 fn selection_changed(&self, mat: Option<&StringMatch>, _window: &mut Window, cx: &mut App) {
694 let div_inspector = self.div_inspector.clone();
695 let rust_completion = mat.as_ref().map(|mat| mat.string.clone());
696 cx.defer(move |cx| {
697 div_inspector.update(cx, |div_inspector, cx| {
698 div_inspector.handle_rust_completion_selection_change(rust_completion, cx);
699 });
700 });
701 }
702
703 fn sort_completions(&self) -> bool {
704 false
705 }
706}
707
708fn completion_replace_range(snapshot: &BufferSnapshot, anchor: &Anchor) -> Option<Range<Anchor>> {
709 let point = anchor.to_point(snapshot);
710 let offset = point.to_offset(snapshot);
711 let line_start = Point::new(point.row, 0).to_offset(snapshot);
712 let line_end = Point::new(point.row, snapshot.line_len(point.row)).to_offset(snapshot);
713 let mut lines = snapshot.text_for_range(line_start..line_end).lines();
714 let line = lines.next()?;
715
716 let start_in_line = &line[..offset - line_start]
717 .rfind(|c| is_not_identifier_char(c) && c != '.')
718 .map(|ix| ix + 1)
719 .unwrap_or(0);
720 let end_in_line = &line[offset - line_start..]
721 .rfind(|c| is_not_identifier_char(c) && c != '(' && c != ')')
722 .unwrap_or(line_end - line_start);
723
724 if end_in_line > start_in_line {
725 let replace_start = snapshot.anchor_before(line_start + start_in_line);
726 let replace_end = snapshot.anchor_after(line_start + end_in_line);
727 Some(replace_start..replace_end)
728 } else {
729 None
730 }
731}