gpui-component 0.11.0

GPUI Component: the styled component library of GPUI Kit, with 60+ desktop UI components for GPUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
use std::rc::Rc;

use gpui::{
    App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,
    Window, prelude::FluentBuilder as _, relative,
};

use super::{EditorState, GutterStyle, Input};
use crate::native_menu::NativeMenu;
use crate::{ActiveTheme as _, RoleOverride, Sizable, Size, StyledExt as _};

/// A code editor takes its rows from the font, so that a smaller or larger
/// font keeps its leading in proportion.
const EDITOR_LINE_HEIGHT: f32 = 1.5;

/// A styled source-code editor.
#[derive(IntoElement)]
pub struct Editor {
    state: Entity<EditorState>,
    gutter_style: GutterStyle,
    style: StyleRefinement,
    size: Size,
    height: Option<DefiniteLength>,
    appearance: bool,
    bordered: bool,
    disabled: bool,
    readonly: bool,
    tab_index: isize,
    role: RoleOverride,
    aria_label: Option<SharedString>,

    /// An optional context menu builder to allow a custom context menu.
    ///
    /// If set, this overrides the built-in context menu.
    context_menu_builder: Option<Rc<dyn Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu>>,

    paste_handler: Option<Rc<dyn Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool>>,
}

impl Editor {
    pub fn new(state: &Entity<EditorState>) -> Self {
        Self {
            state: state.clone(),
            gutter_style: GutterStyle::default(),
            style: StyleRefinement::default(),
            size: Size::default(),
            height: None,
            appearance: true,
            bordered: true,
            disabled: false,
            readonly: false,
            tab_index: 0,
            role: RoleOverride::default(),
            aria_label: None,
            context_menu_builder: None,
            paste_handler: None,
        }
    }

    /// Overrides specified line-number properties for this editor.
    ///
    /// Omitting this on a later render restores the inherited defaults.
    pub fn gutter_style(mut self, style: GutterStyle) -> Self {
        self.gutter_style.apply_overrides(style);
        self
    }

    pub fn h(mut self, height: impl Into<DefiniteLength>) -> Self {
        self.height = Some(height.into());
        self
    }

    pub fn appearance(mut self, appearance: bool) -> Self {
        self.appearance = appearance;
        self
    }

    pub fn bordered(mut self, bordered: bool) -> Self {
        self.bordered = bordered;
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Set the editor to read-only, default is `false`.
    ///
    /// Unlike [`Self::disabled`], a read-only editor keeps the normal appearance
    /// and still can be focused, selected and copied, it only rejects the changes
    /// made by the user.
    pub fn readonly(mut self, readonly: bool) -> Self {
        self.readonly = readonly;
        self
    }

    pub fn tab_index(mut self, index: isize) -> Self {
        self.tab_index = index;
        self
    }

    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
        self.role = role.into();
        self
    }

    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
        self.aria_label = Some(label.into());
        self
    }

    /// Replace the built-in context menu shown on right-click.
    ///
    /// The closure receives an empty menu and returns the one to show, so it
    /// decides entirely what appears — the default items are not added. It
    /// shows only while the state's context menu is enabled, which is the
    /// default.
    pub fn context_menu(
        mut self,
        f: impl Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu + 'static,
    ) -> Self {
        self.context_menu_builder = Some(Rc::new(f));
        self
    }

    /// Intercept paste payloads (images, files) before the default text insertion.
    ///
    /// `true` consumes the paste so nothing is inserted, `false` falls through
    /// to `clipboard.text()`. Copied files arrive as `ExternalPaths` through
    /// the same hook. On web the clipboard reads `None`; image paste needs
    /// async clipboard access and is out of scope.
    pub fn on_paste(
        mut self,
        handler: impl Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool + 'static,
    ) -> Self {
        self.paste_handler = Some(Rc::new(handler));
        self
    }
}

/// Match the padding and density of Input and Textarea in the same form by
/// applying the same size tier. The editor keeps its independently configured
/// code font size and line height.
impl Sizable for Editor {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.size = size.into();
        self
    }
}

impl Styled for Editor {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for Editor {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        Input::from_state(self.state.clone())
            .gutter_style(self.gutter_style)
            // Source code wants a monospace font at a code size, and rows that
            // follow that size. These come first so that a text style set on
            // this editor refines over them: `.text_sm()` and `.font_family()`
            // keep working.
            .font_family(cx.theme().mono_font_family.clone())
            .text_size(cx.theme().mono_font_size)
            .line_height(relative(EDITOR_LINE_HEIGHT))
            .with_size(self.size)
            .appearance(self.appearance)
            .bordered(self.bordered)
            .focus_bordered(false)
            .disabled(self.disabled)
            .readonly(self.readonly)
            .tab_index(self.tab_index)
            .role(self.role)
            .when_some(self.height, |this, height| this.h(height))
            .when_some(self.aria_label, |this, label| this.aria_label(label))
            .when_some(self.context_menu_builder, |this, build| {
                this.context_menu(move |menu, window, cx| build(menu, window, cx))
            })
            .when_some(self.paste_handler, |this, handler| {
                this.on_paste(move |item, window, cx| handler(item, window, cx))
            })
            .refine_style(&self.style)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::EditorState;
    use gpui::{
        AppContext as _, Context, InteractiveElement as _, ParentElement as _, Pixels, Render,
        TestAppContext, VisualTestContext, div, px, rems,
    };

    #[gpui::test]
    fn test_editor_gutter_style_builder(cx: &mut TestAppContext) {
        cx.update(crate::init);
        cx.add_window_view(|window, cx| {
            let state = cx.new(|cx| EditorState::new(window, cx));
            let defaults = GutterStyle::default()
                .with_gap(px(12.))
                .with_line_number_color(gpui::rgb(0x808080).into())
                .with_active_line_number_color(gpui::rgb(0xeeeeee).into())
                .with_line_number_font_family("Number Font")
                .with_line_number_font_size(px(12.));
            let editor = Editor::new(&state)
                .gutter_style(defaults.clone())
                .gutter_style(GutterStyle::default().with_gap(px(0.)));
            assert_eq!(editor.gutter_style, defaults.with_gap(px(0.)));
            Harness {
                state,
                text_size: None,
            }
        });
    }

    struct GutterHarness {
        state: Entity<EditorState>,
        overrides: Option<GutterStyle>,
    }

    impl Render for GutterHarness {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().child(
                Editor::new(&self.state)
                    .font_family(".SystemUIFont")
                    .text_size(rems(1.))
                    .when_some(self.overrides.clone(), |this, style| {
                        this.gutter_style(style)
                    }),
            )
        }
    }

    #[gpui::test]
    fn gutter_overrides_and_removal_reach_the_rendered_editor(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (view, cx) = cx.add_window_view(|window, cx| GutterHarness {
            state: cx.new(|cx| EditorState::new(window, cx).default_value("hello\nworld")),
            overrides: None,
        });
        let state = view.read_with(cx, |view, _| view.state.clone());
        let measure = |cx: &mut VisualTestContext| {
            cx.update(|window, cx| {
                window.refresh();
                window.draw(cx).clear(cx);
                let state = state.read(cx);
                let caret = state
                    .prepaint_caret_geometry()
                    .expect("editor must prepaint");
                (
                    caret.cursor_bounds().left() - caret.input_bounds().left(),
                    caret.line_height(),
                    state.range_to_bounds(&(0..1)).unwrap().size.width,
                )
            })
        };
        let baseline = measure(cx);

        view.update(cx, |view, cx| {
            view.overrides = Some(
                GutterStyle::default()
                    .with_gap(px(18.))
                    .with_line_number_font_family(".SystemUIFont")
                    .with_line_number_font_size(px(16.)),
            );
            cx.notify();
        });
        let configured = measure(cx);
        assert_eq!(configured.0 - baseline.0, px(12.));
        assert_eq!((configured.1, configured.2), (baseline.1, baseline.2));

        view.update(cx, |view, cx| {
            view.overrides = Some(GutterStyle::default().with_gap(px(0.)));
            cx.notify();
        });
        let overridden = measure(cx);
        assert_eq!(configured.0 - overridden.0, px(18.));

        view.update(cx, |view, cx| {
            view.overrides = Some(
                GutterStyle::default()
                    .with_gap(px(0.))
                    .with_line_number_font_size(px(24.)),
            );
            cx.notify();
        });
        let changed = measure(cx);
        // Gutter typography must remain independent of the body metrics.
        assert!(changed.0 > overridden.0);
        assert_eq!((changed.1, changed.2), (baseline.1, baseline.2));

        view.update(cx, |view, cx| {
            view.overrides = Some(
                GutterStyle::default()
                    .with_gap(px(24.))
                    .with_line_number_font_size(px(24.)),
            );
            cx.notify();
        });
        let restored = measure(cx);
        assert_eq!(restored.0 - changed.0, px(24.));

        view.update(cx, |view, cx| {
            view.overrides = None;
            cx.notify();
        });
        assert_eq!(measure(cx), baseline);
    }

    struct Harness {
        state: Entity<EditorState>,
        /// A text size set on the editor, as `.text_sm()` would.
        text_size: Option<Pixels>,
    }

    impl Render for Harness {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().child(
                Editor::new(&self.state)
                    .when_some(self.text_size, |this, size| this.text_size(size)),
            )
        }
    }

    #[gpui::test]
    fn gutter_and_body_follow_window_zoom_without_compounding(cx: &mut TestAppContext) {
        use crate::{ElementExt as _, Root, Theme, init};
        use std::cell::Cell;

        struct ZoomHarness {
            editor: Entity<GutterHarness>,
            spacing_edges: Rc<Cell<(Pixels, Pixels)>>,
        }

        impl Render for ZoomHarness {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                let first = self.spacing_edges.clone();
                let second = self.spacing_edges.clone();
                div()
                    .relative()
                    .size_full()
                    .child(self.editor.clone())
                    .child(
                        div()
                            .absolute()
                            .flex()
                            .gap_2()
                            .child(div().w(px(1.)).h(px(1.)).on_prepaint(move |bounds, _, _| {
                                first.set((bounds.right(), first.get().1));
                            }))
                            .child(div().w(px(1.)).h(px(1.)).on_prepaint(move |bounds, _, _| {
                                second.set((second.get().0, bounds.left()));
                            })),
                    )
            }
        }

        cx.update(|cx| {
            init(cx);
            Theme::update(cx, |theme| theme.font_size = px(22.));
        });
        let spacing_edges = Rc::new(Cell::new((px(0.), px(0.))));
        let mut view = None;
        let (_, cx) = cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| GutterHarness {
                state: cx.new(|cx| {
                    EditorState::new(window, cx)
                        .folding(false)
                        .default_value("hello\nworld")
                }),
                overrides: Some(
                    GutterStyle::default()
                        .with_gap(rems(0.75))
                        .with_line_number_font_size(rems(0.75)),
                ),
            });
            view = Some(editor.clone());
            let content = cx.new(|_| ZoomHarness {
                editor,
                spacing_edges: spacing_edges.clone(),
            });
            // Mount the production root to exercise Kit's theme-driven rem scale.
            Root::new(content, window, cx)
        });
        let view = view.unwrap();
        let state = view.read_with(cx, |view, _| view.state.clone());
        let measure = |cx: &mut VisualTestContext, rem_size: Option<f32>| {
            cx.update(|window, cx| {
                if let Some(rem_size) = rem_size {
                    Theme::update(cx, |theme| theme.font_size = px(rem_size));
                }
                // Verify that window zoom survives independently rendered frames.
                for _ in 0..2 {
                    window.refresh();
                    window.draw(cx).clear(cx);
                }
                let caret = state.read(cx).prepaint_caret_geometry().unwrap();
                let (first_right, second_left) = spacing_edges.get();
                (
                    caret.cursor_bounds().left() - caret.input_bounds().left(),
                    caret.line_height(),
                    second_left - first_right,
                    window.rem_size(),
                )
            })
        };
        let initial = measure(cx, None);
        assert_eq!(
            (initial.1, initial.2, initial.3),
            (px(33.), px(11.), px(22.))
        );
        let baseline = measure(cx, Some(16.));
        for (rem_size, scale, expected_height) in [
            (12., 0.75, 18.),
            (24., 1.5, 36.),
            (32., 2., 48.),
            (16., 1., 24.),
        ] {
            let measured = measure(cx, Some(rem_size));
            let expected_width = baseline.0 * scale;
            // Shaping and gutter-coordinate subtraction round independently in
            // f32; allow arithmetic roundoff rather than a visible pixel offset.
            let tolerance = measured.0.abs().max(expected_width.abs()) * (4. * f32::EPSILON);
            assert!((measured.0 - expected_width).abs() <= tolerance);
            assert_eq!(measured.1, px(expected_height));
            assert_eq!(measured.2, px(rem_size * 0.5));
            assert_eq!(measured.3, px(rem_size));
        }
        assert_eq!(measure(cx, Some(16.)), baseline);
        assert_eq!(measure(cx, None), baseline);
        let zoomed = measure(cx, Some(24.));
        assert_eq!(measure(cx, None), zoomed);
        view.read_with(cx, |view, _| {
            let style = view.overrides.as_ref().unwrap();
            assert_eq!(style.gap(), Some(rems(0.75).into()));
            assert_eq!(style.line_number_font_size(), Some(rems(0.75).into()));
        });
    }

    /// The row height the editor laid out with, which follows its font size.
    fn line_height(cx: &mut TestAppContext, text_size: Option<Pixels>) -> Pixels {
        cx.update(crate::init);
        let mut state = None;
        let (_, cx) = cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| EditorState::new(window, cx).default_value("fn main() {}"));
            state = Some(editor.clone());
            Harness {
                state: editor,
                text_size,
            }
        });
        let state = state.unwrap();
        VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));

        cx.read(|cx| {
            state
                .read(cx)
                .line_height()
                .expect("the editor must lay out")
        })
    }

    #[gpui::test]
    fn the_rows_follow_the_font_size(cx: &mut TestAppContext) {
        // With nothing set, the theme's monospace size, not the ambient one.
        assert_eq!(line_height(cx, None), px(20.));
        // A text style set on the editor refines over that, rows and all.
        assert_eq!(line_height(cx, Some(px(24.))), px(36.));
        assert_eq!(line_height(cx, Some(px(40.))), px(60.));
    }

    struct SizedHarness {
        state: Entity<EditorState>,
        /// A size set on the editor; `None` leaves the default.
        size: Option<Size>,
    }

    impl Render for SizedHarness {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().debug_selector(|| "frame".into()).size_full().child(
                Editor::new(&self.state).when_some(self.size, |this, size| this.with_size(size)),
            )
        }
    }

    /// How far the text starts below the top of the editor's frame, and the
    /// row height it laid out with.
    fn top_inset(cx: &mut TestAppContext, size: Option<Size>) -> (Pixels, Pixels) {
        cx.update(crate::init);
        let mut state = None;
        let (_, cx) = cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| EditorState::new(window, cx).default_value("fn main() {}"));
            state = Some(editor.clone());
            SizedHarness {
                state: editor,
                size,
            }
        });
        let state = state.unwrap();
        VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));

        let frame = cx.debug_bounds("frame").expect("the frame must lay out");
        let (text, line_height) = cx.read(|cx| {
            let state = state.read(cx);
            let line_height = state.line_height().expect("the editor must lay out");
            (state.input_bounds(), line_height)
        });
        (text.top() - frame.top(), line_height)
    }

    #[gpui::test]
    fn the_insets_follow_the_size(cx: &mut TestAppContext) {
        let (medium, rows) = top_inset(cx, Some(Size::Medium));
        // With no size set, the editor keeps the medium insets it always had.
        assert_eq!(top_inset(cx, None), (medium, rows));
        for size in [Size::XSmall, Size::Small, Size::Large] {
            let (inset, line_height) = top_inset(cx, Some(size));
            assert_eq!(
                medium - inset,
                Size::Medium.input_py() - size.input_py(),
                "{size:?}"
            );
            // Only the insets change, not the font.
            assert_eq!(line_height, rows, "{size:?}");
        }
    }

    #[gpui::test]
    fn language_config_works_without_render_sync(cx: &mut TestAppContext) {
        use crate::input::{AutoClosingPair, language_config::LanguageConfig, set_language_config};
        use gpui::EntityInputHandler as _;
        cx.update(crate::init);
        let mut state = None;
        let (_, cx) = cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| EditorState::new(window, cx).language("plaintext"));
            // Plain-text defaults apply before the first render.
            editor.update(cx, |state, cx| {
                state.replace_text_in_range(None, "(", window, cx);
                assert_eq!(state.text().to_string(), "(");
                state.set_value("", window, cx);
                state.set_highlighter("json", cx);
                state.replace_text_in_range(None, "[", window, cx);
                assert_eq!(state.text().to_string(), "[]");
            });
            state = Some(editor.clone());
            Harness {
                state: editor,
                text_size: None,
            }
        });
        let state = state.unwrap();
        VisualTestContext::update(cx, |_, cx| {
            set_language_config(
                "json",
                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
                cx,
            );
        });
        // A styled render must preserve the registered configuration.
        VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));
        VisualTestContext::update(cx, |window, cx| {
            state.update(cx, |state, cx| {
                state.set_value("", window, cx);
                state.replace_text_in_range(None, "«", window, cx);
                assert_eq!(state.text().to_string(), "«»");
                state.set_value("if enabled:", window, cx);
                state.set_selected_range(11..11, cx);
                state.set_highlighter("python", cx);
                state.focus(window, cx);
            });
        });
        VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));
        cx.simulate_keystrokes("enter");
        cx.read(|cx| assert_eq!(state.read(cx).text().to_string(), "if enabled:\n  "));
    }

    #[gpui::test]
    fn aliases_share_config_even_when_registered_before_init(cx: &mut TestAppContext) {
        use crate::input::{AutoClosingPair, language_config::LanguageConfig, set_language_config};
        use gpui::EntityInputHandler as _;
        cx.update(|cx| {
            set_language_config(
                "py",
                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
                cx,
            )
        });
        cx.update(crate::init);
        cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| EditorState::new(window, cx).language("PYTHON"));
            editor.update(cx, |state, cx| {
                state.replace_text_in_range(None, "«", window, cx);
                assert_eq!(state.text().to_string(), "«»");
            });
            set_language_config("pyi", LanguageConfig::default().auto_closing_pairs([]), cx);
            editor.update(cx, |state, cx| {
                state.set_value("", window, cx);
                state.set_highlighter("py", cx);
                state.replace_text_in_range(None, "(", window, cx);
                assert_eq!(state.text().to_string(), "(");
            });
            Harness {
                state: editor,
                text_size: None,
            }
        });
    }

    #[cfg(all(feature = "tree-sitter-python", feature = "tree-sitter-rust"))]
    #[gpui::test]
    fn syntax_follows_language_before_first_render_and_after_switch(cx: &mut TestAppContext) {
        use gpui::EntityInputHandler as _;
        cx.update(crate::init);
        cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| {
                EditorState::new(window, cx)
                    .language("python")
                    .default_value("\"hello world\"")
            });
            editor.update(cx, |state, cx| {
                state.set_selected_range(6..6, cx);
                state.replace_text_in_range(None, "(", window, cx);
                assert_eq!(state.text().to_string(), "\"hello( world\"");
                state.set_value("# comment ", window, cx);
                state.set_selected_range(10..10, cx);
                state.replace_text_in_range(None, "(", window, cx);
                assert_eq!(state.text().to_string(), "# comment (");
                state.set_value("# comment ", window, cx);
                state.set_selected_range(10..10, cx);
                state.set_highlighter("rust", cx);
                state.replace_text_in_range(None, "(", window, cx);
                assert_eq!(state.text().to_string(), "# comment ()");
            });
            Harness {
                state: editor,
                text_size: None,
            }
        });
    }

    #[cfg(feature = "tree-sitter-python")]
    #[gpui::test]
    fn python_pairing_uses_pre_edit_context(cx: &mut TestAppContext) {
        use gpui::EntityInputHandler as _;
        cx.update(crate::init);
        for (before, cursor, typed, expected) in [
            ("x = ", 4, "\"", "x = \"\""),
            ("x = f\"{value}\"", 12, "(", "x = f\"{value()}\""),
            ("x = \"value\"", 7, "(", "x = \"va(lue\""),
            ("x = \"value\"", 5, "(", "x = \"(value\""),
            ("x = \"value\"", 10, "(", "x = \"value(\""),
        ] {
            let mut state = None;
            let (_, cx) = cx.add_window_view(|window, cx| {
                let editor = cx.new(|cx| EditorState::new(window, cx).default_value(before));
                state = Some(editor.clone());
                Harness {
                    state: editor,
                    text_size: None,
                }
            });
            let state = state.unwrap();
            VisualTestContext::update(cx, |window, cx| {
                state.update(cx, |state, cx| {
                    state.set_highlighter("python", cx);
                    state.set_selected_range(cursor..cursor, cx);
                    state.replace_text_in_range(None, typed, window, cx);
                    assert_eq!(state.text().to_string(), expected);
                });
            });
        }
    }
    #[cfg(feature = "tree-sitter-rust")]
    #[gpui::test]
    fn generated_comment_closer_survives_syntax_changes(cx: &mut TestAppContext) {
        use crate::input::{AutoClosingPair, SyntaxContext, language_config::LanguageConfig};
        use gpui::EntityInputHandler as _;
        cx.update(crate::init);
        cx.update(|cx| {
            crate::input::set_language_config(
                "rust",
                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("/*", "*/")
                    .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
                cx,
            )
        });
        let mut state = None;
        let (_, cx) = cx.add_window_view(|window, cx| {
            let editor = cx.new(|cx| EditorState::new(window, cx).language("rust"));
            state = Some(editor.clone());
            Harness {
                state: editor,
                text_size: None,
            }
        });
        let state = state.unwrap();
        VisualTestContext::update(cx, |window, cx| {
            state.update(cx, |state, cx| {
                state.set_highlighter("rust", cx);

                for text in ["/", "*", "x", "*", "/"] {
                    state.replace_text_in_range(None, text, window, cx);
                }
                assert_eq!(state.text().to_string(), "/*x*/");
                state.replace_text_in_range(None, "!", window, cx);
                assert_eq!(state.text().to_string(), "/*x*/!");
            });
        });
    }

    #[gpui::test]
    fn test_on_paste_builder(cx: &mut TestAppContext) {
        use gpui::{AppContext as _, Render};

        struct PasteProbe;
        impl Render for PasteProbe {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                div()
            }
        }

        cx.update(crate::init);
        let _ = cx.add_window_view(|window, cx| {
            let state = cx.new(|cx| EditorState::new(window, cx));
            assert!(Editor::new(&state).paste_handler.is_none());
            let editor = Editor::new(&state).on_paste(|_, _, _| true);
            assert!(editor.paste_handler.is_some());
            PasteProbe
        });
    }
}