iced-code-editor 0.7.1

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! Iced UI view and rendering logic.

use iced::Size;
use iced::alignment;
use iced::mouse;
use iced::widget::canvas::Canvas;
use iced::widget::{
    Column, MouseArea, Row, Scrollable, Space, container, scrollable, text,
};
use iced::{Background, Border, Color, Element, Length, Rectangle, Shadow};
use iced_aw::ContextMenu;

use super::text::{expand_tabs, expand_tabs_visible};
use super::wrapping::{self, WrappingCalculator};
use crate::buffer::text_utils::char_range_to_byte_range;
use crate::canvas_editor::features::command_palette::dialog as command_palette_dialog;
use crate::canvas_editor::features::context_menu;
use crate::canvas_editor::features::goto_line::dialog as goto_line_dialog;
use crate::canvas_editor::features::search::dialog as search_dialog;
use crate::canvas_editor::features::sticky_scroll;
use crate::canvas_editor::input::ime_requester::ImeRequester;
use crate::canvas_editor::virtual_text::LineRun;
use crate::canvas_editor::{CodeEditor, Message, TAB_WIDTH};
use std::rc::Rc;

/// Horizontal gap in pixels between the gutter and the code text, matching the
/// offset the canvas text layer uses so pinned headers line up with the code.
const CODE_TEXT_LEFT_PADDING: f32 = 5.0;

/// Thickness in pixels of the separator drawn under the sticky-scroll headers.
const STICKY_SEPARATOR_WIDTH: f32 = 1.0;

/// Rail width in pixels of the canvas editor's scrollbars (the area that takes
/// the mouse).
const SCROLLBAR_WIDTH: f32 = 8.0;
/// Width in pixels of the scroller (thumb) inside the rail.
const SCROLLER_WIDTH: f32 = 6.0;
/// Space in pixels between the scrollbar and the editor's edge.
const SCROLLBAR_MARGIN: f32 = 2.0;

/// The canvas editor's scrollbar: a thin pill, away from the edge.
fn canvas_scrollbar() -> scrollable::Scrollbar {
    scrollable::Scrollbar::new()
        .width(SCROLLBAR_WIDTH)
        .scroller_width(SCROLLER_WIDTH)
        .margin(SCROLLBAR_MARGIN)
}

/// How opaque the scroller is: faint with the mouse away from the editor,
/// plain over it, solid over the scrollbar or while dragging it. Returns the
/// (vertical, horizontal) factors.
fn scroller_alpha(status: scrollable::Status) -> (f32, f32) {
    let pick = |on_bar: bool| if on_bar { 1.0 / 0.6 } else { 1.0 };
    match status {
        scrollable::Status::Active { .. } => (0.6, 0.6),
        scrollable::Status::Hovered {
            is_vertical_scrollbar_hovered: v,
            is_horizontal_scrollbar_hovered: h,
            ..
        } => (pick(v), pick(h)),
        scrollable::Status::Dragged {
            is_vertical_scrollbar_dragged: v,
            is_horizontal_scrollbar_dragged: h,
            ..
        } => (pick(v), pick(h)),
    }
}

/// Builds the transparent-container scrollable style shared by the canvas
/// editor's vertical and horizontal scrollbars: pill-shaped scrollers whose
/// opacity follows the mouse (see [`scroller_alpha`]).
fn canvas_scrollbar_style(
    scrollbar_bg: Color,
    scroller_color: Color,
    status: scrollable::Status,
) -> scrollable::Style {
    let (v, h) = scroller_alpha(status);
    let scale =
        |a: f32| Color { a: (scroller_color.a * a).min(1.0), ..scroller_color };
    // A radius larger than the scroller: the renderer caps it at half the
    // side, so the ends are round.
    let pill = SCROLLBAR_WIDTH * 10.0;
    scrollable::Style {
        container: container::Style {
            background: Some(Background::Color(Color::TRANSPARENT)),
            ..container::Style::default()
        },
        vertical_rail: scrollable_rail(scrollbar_bg, scale(v), pill),
        horizontal_rail: scrollable_rail(scrollbar_bg, scale(h), pill),
        gap: None,
        auto_scroll: scrollable::AutoScroll {
            background: Color::TRANSPARENT.into(),
            border: Border::default(),
            shadow: Shadow::default(),
            icon: Color::TRANSPARENT,
        },
    }
}

impl CodeEditor {
    /// Calculates visual lines and canvas height for the editor.
    ///
    /// Returns a tuple of (visual_lines, canvas_height) where:
    /// - visual_lines: The visual line mapping with wrapping applied
    /// - canvas_height: The total height needed for the canvas
    fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
        // Reuse memoized visual lines so view layout (canvas height + IME cursor rect)
        // does not trigger repeated wrapping computation.
        let visual_lines = self.visual_lines_cached(self.viewport_width);
        let total_visual_lines = visual_lines.len();
        let content_height = total_visual_lines as f32 * self.line_height;

        // Use max of content height and viewport height to ensure the canvas
        // always covers the visible area (prevents visual artifacts when
        // content is shorter than viewport after reset/file change)
        let canvas_height = content_height.max(self.viewport_height);

        (visual_lines, canvas_height)
    }

    /// Creates the scrollable style function with custom colors.
    ///
    /// Returns a style function that configures the scrollbar appearance.
    fn create_scrollable_style(
        &self,
    ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
        let scrollbar_bg = self.style.scrollbar_background;
        let scroller_color = self.style.scroller_color;

        move |_theme, status| {
            canvas_scrollbar_style(scrollbar_bg, scroller_color, status)
        }
    }

    /// Creates the canvas widget wrapped in a scrollable container.
    ///
    /// # Arguments
    ///
    /// * `canvas_height` - The total height of the canvas
    ///
    /// # Returns
    ///
    /// A configured scrollable widget containing the canvas
    fn create_canvas_with_scrollable(
        &self,
        canvas_height: f32,
    ) -> Scrollable<'_, Message> {
        let canvas = Canvas::new(self)
            .width(Length::Fill)
            .height(Length::Fixed(canvas_height));

        Scrollable::new(canvas)
            .id(self.scrollable_id.clone())
            .width(Length::Fill)
            .height(Length::Fill)
            .direction(scrollable::Direction::Vertical(canvas_scrollbar()))
            .on_scroll(Message::Scrolled)
            .style(self.create_scrollable_style())
    }

    /// Decides whether the horizontal scrollbar should be shown: wrap must be
    /// disabled, and the widest line must not fit in the real, last-observed
    /// canvas width (`last_canvas_width`, refreshed every `draw()` call).
    ///
    /// This intentionally does not use `viewport_width`, which is only
    /// corrected via vertical-scroll notifications and can stay stuck at its
    /// default for content that never overflows vertically — e.g. right after
    /// [`CodeEditor::reset`] loads a short file with a very wide line (issue #26).
    ///
    /// # Arguments
    ///
    /// * `max_content_width` - The total pixel width of the widest line
    ///
    /// # Returns
    ///
    /// `true` if a horizontal scrollbar is needed, `false` otherwise
    pub(crate) fn should_show_horizontal_scrollbar(
        &self,
        max_content_width: f32,
    ) -> bool {
        !self.wrap_enabled && max_content_width > self.last_canvas_width.get()
    }

    /// Creates the horizontal scrollbar element when wrap is disabled and content overflows.
    ///
    /// # Arguments
    ///
    /// * `max_content_width` - The total pixel width of the widest line
    ///
    /// # Returns
    ///
    /// `Some(element)` if a horizontal scrollbar is needed, `None` otherwise
    fn create_horizontal_scrollbar(
        &self,
        max_content_width: f32,
    ) -> Option<Element<'_, Message>> {
        if !self.should_show_horizontal_scrollbar(max_content_width) {
            return None;
        }

        let scrollbar_bg = self.style.scrollbar_background;
        let scroller_color = self.style.scroller_color;

        let h_scrollable = Scrollable::new(
            Space::new().width(Length::Fixed(max_content_width)).height(0.0),
        )
        .id(self.horizontal_scrollable_id.clone())
        .width(Length::Fill)
        .height(Length::Fixed(12.0))
        .direction(scrollable::Direction::Horizontal(canvas_scrollbar()))
        .on_scroll(Message::HorizontalScrolled)
        .style(move |_theme, status| {
            canvas_scrollbar_style(scrollbar_bg, scroller_color, status)
        });

        Some(h_scrollable.into())
    }

    /// Creates the gutter background container if line numbers are enabled.
    ///
    /// # Returns
    ///
    /// Some(container) if line numbers are enabled, None otherwise
    fn create_gutter_container(
        &self,
    ) -> Option<container::Container<'_, Message>> {
        if self.line_numbers_enabled {
            let gutter_background = self.style.gutter_background;
            Some(
                container(
                    Space::new().width(Length::Fill).height(Length::Fill),
                )
                // Spans the fold margin too when it comes first, so the
                // whole gutter left of the numbers shares one background.
                .width(Length::Fixed(self.gutter_columns().line_numbers.end))
                .height(Length::Fill)
                .style(move |_| container::Style {
                    background: Some(Background::Color(gutter_background)),
                    ..container::Style::default()
                }),
            )
        } else {
            None
        }
    }

    /// Creates the code area background container.
    ///
    /// # Returns
    ///
    /// The code background container widget
    fn create_code_background_container(
        &self,
    ) -> container::Container<'_, Message> {
        let background_color = self.style.background;
        container(Space::new().width(Length::Fill).height(Length::Fill))
            .width(Length::Fill)
            .height(Length::Fill)
            .style(move |_| container::Style {
                background: Some(Background::Color(background_color)),
                ..container::Style::default()
            })
    }

    /// Creates the fixed Vim status and command line shown below the editor.
    fn create_vim_status_bar(&self) -> Element<'_, Message> {
        let (left_text, right_text) = self.vim_state.status_line_text();
        let background = self.style.gutter_background;
        let text_color = self.style.text_color;

        container(
            Row::new()
                .push(
                    text(left_text).size(self.font_size).style(move |_| {
                        text::Style { color: Some(text_color) }
                    }),
                )
                .push(Space::new().width(Length::Fill))
                .push(
                    text(right_text).size(self.font_size).style(move |_| {
                        text::Style { color: Some(text_color) }
                    }),
                ),
        )
        .padding([2, 8])
        .width(Length::Fill)
        .height(Length::Fixed(self.line_height.max(20.0)))
        .style(move |_| container::Style {
            background: Some(Background::Color(background)),
            ..container::Style::default()
        })
        .into()
    }

    /// Creates the background layer combining gutter and code backgrounds.
    ///
    /// # Returns
    ///
    /// A row containing the background elements
    fn create_background_layer(&self) -> Row<'_, Message> {
        let gutter_container = self.create_gutter_container();
        let code_background_container = self.create_code_background_container();

        if let Some(gutter) = gutter_container {
            Row::new().push(gutter).push(code_background_container)
        } else {
            Row::new().push(code_background_container)
        }
    }

    /// Calculates the IME cursor rectangle for the current cursor position.
    ///
    /// # Arguments
    ///
    /// * `visual_lines` - The visual line mapping
    ///
    /// # Returns
    ///
    /// A rectangle representing the cursor position for IME
    fn calculate_ime_cursor_rect(
        &self,
        visual_lines: &[wrapping::VisualLine],
    ) -> Rectangle {
        let ime_enabled = self.is_focused() && self.has_canvas_focus;

        if !ime_enabled {
            return Rectangle::new(
                iced::Point::new(0.0, 0.0),
                Size::new(0.0, 0.0),
            );
        }

        if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
            visual_lines,
            self.cursors.primary_position().0,
            self.cursors.primary_position().1,
        ) {
            let cursor_x = self.caret_content_x(
                &visual_lines[cursor_visual],
                self.cursors.primary_position().1,
            ) - self.horizontal_scroll_offset;

            // Calculate visual Y position relative to the viewport
            // We subtract viewport_scroll because the content is scrolled up/down
            // but the cursor position sent to IME must be relative to the visible area
            let cursor_y = (cursor_visual as f32 * self.line_height)
                - self.viewport_scroll;

            Rectangle::new(
                iced::Point::new(cursor_x, cursor_y + 2.0),
                Size::new(2.0, self.line_height - 4.0),
            )
        } else {
            Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
        }
    }

    /// Builds one pinned header row: its line number, then its colored text.
    ///
    /// The row reuses the memoized per-line highlight spans, so pinning a header
    /// costs no extra syntect work. Unlike the canvas text layer, it ignores
    /// `horizontal_scroll_offset`: a pinned header exists to be read, and would
    /// be useless if it scrolled out of view sideways.
    ///
    /// # Arguments
    ///
    /// * `line` - Index of the logical header line to render
    /// * `syntax_set` - The syntax set `syntax` belongs to
    /// * `syntax` - The syntect syntax definition to tokenize with
    /// * `theme` - The syntect theme providing token colors
    fn create_sticky_header_row(
        &self,
        line: usize,
        syntax_set: &syntect::parsing::SyntaxSet,
        syntax: &syntect::parsing::SyntaxReference,
        theme: &syntect::highlighting::Theme,
    ) -> Element<'_, Message> {
        let font = self.font;
        let font_size = self.font_size;
        let line_number_color = self.style.line_number_color;

        let mut row = Row::new();

        // Keep the fold margin empty: a pinned header is not where the user
        // folds, and a chevron there would invite a click that does nothing.
        let fold_margin_width = self.fold_margin_width();
        let fold_margin =
            || Space::new().width(Length::Fixed(fold_margin_width));
        let markers_first = self.fold_marker_position
            == crate::FoldMarkerPosition::BeforeLineNumbers;
        if markers_first {
            row = row.push(fold_margin());
        }

        if self.line_numbers_enabled {
            row = row.push(
                container(
                    text(format!("{}", line + 1))
                        .size(font_size)
                        .font(font)
                        .style(move |_| text::Style {
                            color: Some(line_number_color),
                        }),
                )
                .width(Length::Fixed(self.line_number_gutter_width()))
                .align_x(alignment::Horizontal::Center),
            );
        }

        if !markers_first {
            row = row.push(fold_margin());
        }
        row =
            row.push(Space::new().width(Length::Fixed(CODE_TEXT_LEFT_PADDING)));

        let spans =
            self.highlighted_line_cached(line, syntax, theme, syntax_set);
        let line_content = self.buffer.line(line);
        let cols = (0, self.buffer.line_len(line));
        let mut code = Row::new();
        for run in self.line_runs(line, Some(spans.as_slice()), cols) {
            let (content, color) = match run {
                LineRun::Text { start, end, color } => {
                    let (start_byte, end_byte) =
                        char_range_to_byte_range(line_content, start, end);
                    let content = &line_content[start_byte..end_byte];
                    // Match the canvas text layer, so a pinned header shows
                    // the same whitespace glyphs as the line it mirrors.
                    let content = if self.show_whitespace {
                        expand_tabs_visible(content, TAB_WIDTH)
                    } else {
                        expand_tabs(content, TAB_WIDTH).into_owned()
                    };
                    (content, color)
                }
                LineRun::Virtual(item) => (item.text.clone(), item.color),
            };
            // Unicode headers need the same fallback as the canvas text layer.
            let span_font =
                if content.is_ascii() { font } else { iced::Font::DEFAULT };
            code = code.push(
                text(content)
                    .size(font_size)
                    .font(span_font)
                    .wrapping(text::Wrapping::None)
                    .style(move |_| text::Style { color: Some(color) }),
            );
        }
        row = row.push(code);

        MouseArea::new(
            container(row)
                .width(Length::Fill)
                .height(Length::Fixed(self.line_height))
                .clip(true),
        )
        .interaction(mouse::Interaction::Pointer)
        .on_press(Message::StickyScrollJump(line))
        .into()
    }

    /// Creates the sticky-scroll layer: the headers of the blocks enclosing the
    /// topmost visible line, pinned above the viewport.
    ///
    /// # Arguments
    ///
    /// * `visual_lines` - The visual line mapping, used to resolve the topmost
    ///   visible visual line back to its logical line
    ///
    /// # Returns
    ///
    /// `Some(layer)` when at least one header must be pinned, `None` when the
    /// feature is disabled or the topmost visible line sits at the top level
    fn create_sticky_scroll_layer(
        &self,
        visual_lines: &[wrapping::VisualLine],
    ) -> Option<Element<'_, Message>> {
        if !self.sticky_scroll_enabled || self.line_height <= 0.0 {
            return None;
        }

        // Same first-visible-line formula the canvas layer uses. The topmost
        // entry is a *visual* line, so it must be mapped back to a logical one:
        // wrapping and collapsed folds make the two indices diverge.
        let first_visible =
            (self.viewport_scroll / self.line_height).floor() as usize;
        let top_line = visual_lines.get(first_visible)?.logical_line;

        // `block_regions`, not `foldable_regions`: the blocks a line sits in
        // are a property of the buffer, not of whether the user may collapse
        // them. Sticky scroll keeps working with code folding turned off.
        let regions = self.block_regions();
        let headers = sticky_scroll::sticky_headers(
            &regions,
            top_line,
            sticky_scroll::DEFAULT_MAX_STICKY_LINES,
        );
        if headers.is_empty() {
            return None;
        }

        let (syntax_set, syntax, theme) = self.resolve_syntax();
        let (Some(syntax), Some(theme)) = (syntax, theme) else {
            return None;
        };

        let mut column = Column::new();
        for line in headers {
            column = column.push(
                self.create_sticky_header_row(line, syntax_set, syntax, theme),
            );
        }

        let background = self.style.gutter_background;
        let border_color = self.style.gutter_border;

        // An explicit rule rather than a container shadow: it must sit exactly
        // one pixel under the last header, on top of the code scrolling beneath.
        let column = column.push(
            container(Space::new().width(Length::Fill).height(Length::Fill))
                .width(Length::Fill)
                .height(Length::Fixed(STICKY_SEPARATOR_WIDTH))
                .style(move |_| container::Style {
                    background: Some(Background::Color(border_color)),
                    ..container::Style::default()
                }),
        );

        Some(
            container(column)
                .width(Length::Fill)
                .height(Length::Shrink)
                .style(move |_| container::Style {
                    background: Some(Background::Color(background)),
                    ..container::Style::default()
                })
                .into(),
        )
    }

    /// Creates the IME (Input Method Editor) layer widget.
    ///
    /// # Arguments
    ///
    /// * `cursor_rect` - The rectangle representing the cursor position
    ///
    /// # Returns
    ///
    /// An element containing the IME requester widget
    fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
        let ime_enabled = self.is_focused() && self.has_canvas_focus;

        // The canvas draws preedit on the spot. Supplying it here would also
        // create Iced's over-the-spot paragraph with unbounded layout.
        let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, None);
        iced::Element::new(ime_layer)
    }

    /// Wraps the canvas scrollable in the right-click context menu.
    ///
    /// The menu owns its transient open/close state and positions itself at
    /// the right-click location. Its widget *captures* the right press before
    /// forwarding it to its underlay, and a `Stack` stops delivering a
    /// captured event after its topmost layer. Wrapping the whole editor stack
    /// therefore hid the press from the canvas, which sits below the IME and
    /// dialog layers: no `ContextMenuRequested` was published, so the caret
    /// and selection handling for context clicks never ran.
    ///
    /// A scrollable forwards events to its content whether or not they were
    /// captured, so wrapping only the scrollable keeps the menu over the same
    /// area while the canvas still sees the press.
    fn with_context_menu<'a>(
        &self,
        underlay: impl Into<Element<'a, Message>>,
    ) -> Element<'a, Message> {
        let action_context = self.action_context();
        let custom_context_menu_entries =
            self.custom_context_menu_entries().to_vec();
        let default_context_menu_enabled = self.default_context_menu_enabled();
        let translations = self.translations;
        ContextMenu::new(underlay, move || {
            context_menu::view(
                &custom_context_menu_entries,
                default_context_menu_enabled,
                action_context,
                translations,
            )
        })
        .into()
    }

    /// Creates the view element with scrollable wrapper.
    ///
    /// The backgrounds (editor and gutter) are handled by container styles
    /// to ensure proper clipping when the pane is resized.
    ///
    /// Call this from the host application's `view`, mapping the editor's
    /// [`Message`] into the host's own message type.
    ///
    /// # Returns
    ///
    /// An `Element` rendering the editor, its gutter, and any open overlay
    ///
    /// # Example
    ///
    /// ```
    /// use iced::Element;
    /// use iced_code_editor::{CodeEditor, Message};
    ///
    /// /// The host application's own message type.
    /// #[derive(Debug, Clone)]
    /// enum AppMessage {
    ///     Editor(Message),
    /// }
    ///
    /// fn view(editor: &CodeEditor) -> Element<'_, AppMessage> {
    ///     editor.view().map(AppMessage::Editor)
    /// }
    /// ```
    pub fn view(&self) -> Element<'_, Message> {
        // Calculate canvas height and visual lines
        let (visual_lines, canvas_height) = self.calculate_canvas_height();

        // Create scrollable containing the canvas, with the right-click menu
        // wrapped directly around it (see `with_context_menu`).
        let scrollable = self.with_context_menu(
            self.create_canvas_with_scrollable(canvas_height),
        );

        // Create background layer with gutter and code backgrounds
        let background_row = self.create_background_layer();

        // Build editor stack: backgrounds + scrollable
        let mut editor_stack =
            iced::widget::Stack::new().push(background_row).push(scrollable);

        // Keep a slot for sticky headers even when there are none. Stack diffs
        // children by position: inserting/removing this layer would recreate
        // the dialogs above it, losing their text input focus and selection
        // whenever a search result scrolls across a block boundary.
        editor_stack = editor_stack.push(
            self.create_sticky_scroll_layer(visual_lines.as_ref())
                .unwrap_or_else(|| Space::new().into()),
        );

        // Add IME layer for input method support.
        // The IME requester needs the cursor rect in viewport coordinates, which
        // depends on the current logical↔visual mapping.
        let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
        let ime_layer = self.create_ime_layer(cursor_rect);
        editor_stack = editor_stack.push(ime_layer);

        // Add the compact go-to-line dialog in the top center.
        if self.goto_line_state.is_open {
            let goto_line_dialog = goto_line_dialog::view(
                &self.goto_line_state,
                self.buffer.line_count(),
            );
            let positioned_dialog = container(
                Row::new()
                    .push(Space::new().width(Length::Fill))
                    .push(goto_line_dialog)
                    .push(Space::new().width(Length::Fill)),
            )
            .padding(20)
            .width(Length::Fill)
            .height(Length::Shrink);

            editor_stack = editor_stack.push(positioned_dialog);
        }

        // Add the command palette in the top center, above every other
        // dialog: opening it closes the others, so it is always innermost.
        if self.command_palette_state.is_open {
            let entries = self.command_palette_entries();
            let palette = command_palette_dialog::view(
                &self.command_palette_state,
                &entries,
                &self.translations,
            );
            let positioned_palette = container(
                Row::new()
                    .push(Space::new().width(Length::Fill))
                    .push(palette)
                    .push(Space::new().width(Length::Fill)),
            )
            .padding(20)
            .width(Length::Fill)
            .height(Length::Shrink);

            editor_stack = editor_stack.push(positioned_palette);
        }

        // Wrap the editor stack in a container with clip
        let editor_container = container(editor_stack)
            .width(Length::Fill)
            .height(Length::Fill)
            .clip(true);

        // When wrap is disabled, add a horizontal scrollbar below the editor.
        let editor_body: Element<'_, Message> = if self.wrap_enabled {
            editor_container.into()
        } else {
            // Measuring the widest line scans the entire buffer. It is only
            // needed for the horizontal scrollbar, so never do that work while
            // wrapping is enabled (the default), especially after every edit in
            // a large file.
            let max_content_width = self.max_content_width();
            if let Some(h_scrollbar) =
                self.create_horizontal_scrollbar(max_content_width)
            {
                Column::new().push(editor_container).push(h_scrollbar).into()
            } else {
                editor_container.into()
            }
        };

        let editor_body = if self.search_state.is_open {
            Column::new()
                .push(search_dialog::view(
                    &self.search_state,
                    &self.translations,
                    !self.vim_enabled,
                    !self.goto_line_state.is_open
                        && !self.command_palette_state.is_open,
                ))
                .push(editor_body)
                .width(Length::Fill)
                .height(Length::Fill)
                .into()
        } else {
            editor_body
        };

        if self.vim_enabled {
            Column::new()
                .push(editor_body)
                .push(self.create_vim_status_bar())
                .width(Length::Fill)
                .height(Length::Fill)
                .into()
        } else {
            editor_body
        }
    }
}

/// Builds a plain-color scrollable rail: a solid background track with a
/// solid-color scroller, square corners of `radius`, and no border.
///
/// Shared by the canvas editor's own scrollbars ([`view`]) and the LSP
/// overlay panels ([`lsp::process::overlay`]), which derive their colors from
/// a theme palette instead of plain [`Color`]s.
///
/// # Examples
///
/// ```text
/// let rail = scrollable_rail(Color::BLACK, Color::WHITE, 4.0);
/// ```
pub(crate) fn scrollable_rail(
    background: Color,
    scroller: Color,
    radius: f32,
) -> iced::widget::scrollable::Rail {
    iced::widget::scrollable::Rail {
        background: Some(background.into()),
        border: iced::Border {
            radius: radius.into(),
            width: 0.0,
            color: Color::TRANSPARENT,
        },
        scroller: iced::widget::scrollable::Scroller {
            background: scroller.into(),
            border: iced::Border {
                radius: radius.into(),
                width: 0.0,
                color: Color::TRANSPARENT,
            },
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ime_uses_canvas_preedit_without_a_duplicate_runtime_overlay()
    -> Result<(), &'static str> {
        use iced::advanced::input_method::InputMethod;
        use iced::advanced::{Layout, Shell, layout, renderer::Headless};

        let renderer = iced::futures::executor::block_on(iced::Renderer::new(
            iced::Font::DEFAULT,
            iced::Pixels(13.0),
            Some("tiny-skia"),
        ))
        .ok_or("headless software renderer unavailable")?;
        let mut editor = CodeEditor::new("", "txt");
        editor.focus_for_test();
        let _ = editor.handle_ime_preedit_msg("中文", &Some(0..3));
        let cursor =
            Rectangle::new(iced::Point::new(40.0, 20.0), Size::new(2.0, 18.0));
        let mut layer = editor.create_ime_layer(cursor);
        let mut tree = iced::advanced::widget::Tree::new(&layer);
        let node = layer.as_widget_mut().layout(
            &mut tree,
            &renderer,
            &layout::Limits::new(Size::ZERO, Size::new(500.0, 300.0)),
        );
        let mut messages = Vec::new();
        let mut shell = Shell::new(&mut messages);
        layer.as_widget_mut().update(
            &mut tree,
            &iced::Event::Window(iced::window::Event::RedrawRequested(
                iced::time::Instant::now(),
            )),
            Layout::new(&node),
            mouse::Cursor::Unavailable,
            &renderer,
            &mut iced::advanced::clipboard::Null,
            &mut shell,
            &Rectangle::with_size(Size::new(500.0, 300.0)),
        );
        assert!(matches!(shell.input_method(), InputMethod::Enabled {
            cursor: requested, preedit: None, ..
        } if *requested == cursor));
        Ok(())
    }

    type InputState = iced::widget::text_input::State<
        <iced::Renderer as iced::advanced::text::Renderer>::Paragraph,
    >;

    fn input_states(
        tree: &mut iced::advanced::widget::Tree,
    ) -> Vec<&mut InputState> {
        if tree.tag == iced::advanced::widget::tree::Tag::of::<InputState>() {
            vec![tree.state.downcast_mut::<InputState>()]
        } else {
            tree.children.iter_mut().flat_map(input_states).collect()
        }
    }

    #[test]
    fn search_input_focus_survives_sticky_header_transitions()
    -> Result<(), &'static str> {
        assert_dialog_focus_survives_sticky_header_transitions(false, 0)
    }

    #[test]
    fn replace_input_focus_survives_sticky_header_transitions()
    -> Result<(), &'static str> {
        assert_dialog_focus_survives_sticky_header_transitions(true, 1)
    }

    fn assert_dialog_focus_survives_sticky_header_transitions(
        replace: bool,
        focused_input: usize,
    ) -> Result<(), &'static str> {
        use iced::advanced::{Layout, Shell, layout, renderer::Headless};
        use iced::keyboard::{self, Key, key::Named};

        let renderer = iced::futures::executor::block_on(iced::Renderer::new(
            iced::Font::DEFAULT,
            iced::Pixels(13.0),
            Some("tiny-skia"),
        ))
        .ok_or("headless software renderer unavailable")?;
        let mut editor = CodeEditor::new(
            "fn main() {\n    let needle = 1;\n    let value = needle;\n}",
            "rs",
        );
        let _ = editor.handle_open_search(replace);
        editor.search_state.set_query("needle".into(), &editor.buffer);
        editor.search_state.set_replace_with("replacement".into());
        let mut tree = iced::advanced::widget::Tree::new(editor.view());
        let mut inputs = input_states(&mut tree);
        inputs[focused_input].focus();
        inputs[focused_input].select_range(1, 3);
        let selection = inputs[focused_input].cursor();

        // Searching/navigating to a match scrolls across block boundaries.
        // The sticky header appears and disappears ahead of the dialog.
        for (scroll, key, text) in [
            (editor.line_height(), Key::Named(Named::Backspace), None),
            (0.0, Key::Named(Named::Enter), None),
            (
                editor.line_height(),
                Key::Character("x".into()),
                Some("x".into()),
            ),
        ] {
            editor.viewport_scroll = scroll;
            let visual_lines =
                editor.visual_lines_cached(editor.viewport_width);
            assert_eq!(
                editor.create_sticky_scroll_layer(&visual_lines).is_some(),
                scroll > 0.0,
            );
            let mut view = editor.view();
            tree.diff(&view);
            let inputs = input_states(&mut tree);
            assert!(
                inputs[focused_input].is_focused(),
                "dialog lost focus after scroll"
            );
            assert_eq!(inputs[focused_input].cursor(), selection);

            let node = view.as_widget_mut().layout(
                &mut tree,
                &renderer,
                &layout::Limits::new(Size::ZERO, Size::new(800.0, 400.0)),
            );
            let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
                key: key.clone(),
                modified_key: key.clone(),
                physical_key: keyboard::key::Physical::Unidentified(
                    keyboard::key::NativeCode::Unidentified,
                ),
                location: keyboard::Location::Standard,
                modifiers: keyboard::Modifiers::empty(),
                text,
                repeat: false,
            });
            let mut messages = Vec::new();
            let mut shell = Shell::new(&mut messages);
            view.as_widget_mut().update(
                &mut tree,
                &event,
                Layout::new(&node),
                mouse::Cursor::Unavailable,
                &renderer,
                &mut iced::advanced::clipboard::Null,
                &mut shell,
                &node.bounds(),
            );
            assert!(shell.is_event_captured());
            assert_eq!(messages.len(), 1);
            assert!(
                matches!(
                    (&messages[0], replace, key),
                    (Message::FindNext, false, Key::Named(Named::Enter))
                        | (
                            Message::ReplaceNext,
                            true,
                            Key::Named(Named::Enter)
                        )
                        | (Message::SearchQueryChanged(_), false, _)
                        | (Message::ReplaceQueryChanged(_), true, _)
                ),
                "key escaped the dialog: {messages:?}"
            );
            input_states(&mut tree)[focused_input].select_range(1, 3);
        }
        Ok(())
    }

    #[test]
    fn test_should_show_horizontal_scrollbar_after_reset_with_known_canvas_width()
     {
        // Regression test for issue #26: a prior real `draw()` call already
        // recorded the true (narrow) canvas width before `reset()` swaps in
        // wide content that never overflows vertically. The decision must use
        // that observed width, not the stale `viewport_width` default.
        let mut editor = CodeEditor::new("short\n", "rs");
        editor.wrap_enabled = false;
        editor.last_canvas_width.set(200.0);

        let _ = editor
            .reset("a very very very long single line that clearly exceeds two hundred pixels of rendered width");

        let max_content_width = editor.max_content_width();
        assert!(
            editor.should_show_horizontal_scrollbar(max_content_width),
            "wide content narrower canvas should require a horizontal scrollbar after reset()"
        );
    }

    #[test]
    fn test_should_show_horizontal_scrollbar_false_when_content_fits() {
        let mut editor = CodeEditor::new("short", "rs");
        editor.wrap_enabled = false;
        editor.last_canvas_width.set(800.0);

        let max_content_width = editor.max_content_width();
        assert!(
            !editor.should_show_horizontal_scrollbar(max_content_width),
            "content narrower than the canvas should not need a horizontal scrollbar"
        );
    }

    #[test]
    fn test_should_show_horizontal_scrollbar_false_when_wrap_enabled() {
        let mut editor = CodeEditor::new(
            "a very very very long single line that clearly exceeds two hundred pixels of rendered width",
            "rs",
        );
        editor.wrap_enabled = true;
        editor.last_canvas_width.set(50.0);

        let max_content_width = editor.max_content_width();
        assert!(
            !editor.should_show_horizontal_scrollbar(max_content_width),
            "wrapped content never needs a horizontal scrollbar regardless of width"
        );
    }

    #[test]
    fn test_scrollable_rail_sets_background_scroller_and_radius() {
        let bg = Color::from_rgb(0.1, 0.2, 0.3);
        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
        let rail = scrollable_rail(bg, scroller, 4.0);

        assert_eq!(rail.background, Some(iced::Background::Color(bg)));
        assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
        assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
        assert!(rail.border.width.abs() < f32::EPSILON);
        assert_eq!(
            rail.scroller.border.radius,
            iced::border::Radius::from(4.0)
        );
    }

    #[test]
    fn test_sticky_layer_absent_when_disabled() {
        let mut editor =
            CodeEditor::new("fn main() {\n    let x = 1;\n}", "rs");
        editor.set_sticky_scroll_enabled(false);
        let visual_lines = editor.visual_lines_cached(editor.viewport_width);

        assert!(
            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
        );
    }

    #[test]
    fn test_sticky_layer_absent_without_enclosing_block() {
        // A flat buffer has no fold region, so nothing can be pinned.
        let editor = CodeEditor::new("a\nb\nc", "rs");
        let visual_lines = editor.visual_lines_cached(editor.viewport_width);

        assert!(
            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
        );
    }

    #[test]
    fn test_sticky_layer_absent_at_top_of_file() {
        // Scrolled to the top, the header is on screen and must not be pinned.
        let editor = CodeEditor::new(
            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
            "rs",
        );
        let visual_lines = editor.visual_lines_cached(editor.viewport_width);

        assert!(
            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
        );
    }

    #[test]
    fn test_sticky_layer_survives_code_folding_being_disabled() {
        // End-to-end counterpart of
        // `sticky_scroll::tests::test_headroom_survives_code_folding_being_disabled`:
        // the layer is built from `block_regions`, so turning folding off
        // removes the chevrons and leaves the pinned headers alone.
        let mut editor = CodeEditor::new(
            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
            "rs",
        );
        editor.set_folding_enabled(false);
        editor.viewport_scroll = editor.line_height();
        let visual_lines = editor.visual_lines_cached(editor.viewport_width);

        assert!(
            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
        );
    }

    #[test]
    fn test_sticky_layer_maps_a_wrapped_segment_back_to_its_logical_line() {
        // The subtlest line in the feature: the topmost entry of the viewport
        // is a *visual* line, and soft wrapping makes visual and logical
        // indices diverge. Here the body of the `if` wraps into several
        // segments, so scrolling onto one of its continuations puts the
        // topmost visual index well past any logical line index.
        //
        // The fixture discriminates: reading the visual index as a logical one
        // would land on `}` or past the end of the buffer, where nothing
        // encloses anything and the layer would be `None`.
        let mut editor = CodeEditor::new(
            "fn main() {\n    if a {\n        let x = 1; let y = 2; let z = 3; let w = 4;\n    }\n}",
            "rs",
        )
        .with_wrap_column(Some(20));

        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
        let continuation = visual_lines
            .iter()
            .position(|line| line.logical_line == 2 && line.segment_index == 1)
            .unwrap_or_default();
        assert!(
            continuation > 2,
            "the fixture must wrap far enough for the two indices to diverge"
        );

        editor.viewport_scroll = continuation as f32 * editor.line_height();
        let visual_lines = editor.visual_lines_cached(editor.viewport_width);

        assert!(
            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some(),
            "a continuation segment is still inside both enclosing blocks"
        );
        // Both headers, so the layer really resolved logical line 2 and not
        // whatever line the raw visual index points at.
        assert_eq!(editor.sticky_headroom(2), 2);
    }

    #[test]
    fn test_sticky_layer_present_when_scrolled_into_block() {
        let mut editor = CodeEditor::new(
            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
            "rs",
        );
        // Scroll so the second line is the topmost visible one, putting the
        // viewport inside the `fn` block.
        editor.viewport_scroll = editor.line_height();
        let visual_lines = editor.visual_lines_cached(editor.viewport_width);

        assert!(
            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
        );
    }

    #[test]
    fn test_canvas_scrollbar_style_uses_transparent_container() {
        let bg = Color::from_rgb(0.1, 0.2, 0.3);
        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
        let active = scrollable::Status::Active {
            is_horizontal_scrollbar_disabled: false,
            is_vertical_scrollbar_disabled: false,
        };
        let style = canvas_scrollbar_style(bg, scroller, active);

        assert_eq!(
            style.container.background,
            Some(Background::Color(Color::TRANSPARENT))
        );
        let expected_rail = scrollable_rail(bg, scroller, 4.0);
        assert_eq!(style.vertical_rail.background, expected_rail.background);
        assert_eq!(style.horizontal_rail.background, expected_rail.background);
    }

    #[test]
    fn test_canvas_scroller_is_faint_away_and_solid_on_the_bar() {
        let bg = Color::TRANSPARENT;
        let scroller = Color::from_rgba(0.4, 0.5, 0.6, 0.6);
        let alpha = |status| match canvas_scrollbar_style(bg, scroller, status)
            .vertical_rail
            .scroller
            .background
        {
            Background::Color(c) => c.a,
            // Not a solid color: NaN makes every comparison below fail.
            _ => f32::NAN,
        };
        let away = alpha(scrollable::Status::Active {
            is_horizontal_scrollbar_disabled: false,
            is_vertical_scrollbar_disabled: false,
        });
        let over = alpha(scrollable::Status::Hovered {
            is_horizontal_scrollbar_hovered: false,
            is_vertical_scrollbar_hovered: false,
            is_horizontal_scrollbar_disabled: false,
            is_vertical_scrollbar_disabled: false,
        });
        let on_bar = alpha(scrollable::Status::Dragged {
            is_horizontal_scrollbar_dragged: false,
            is_vertical_scrollbar_dragged: true,
            is_horizontal_scrollbar_disabled: false,
            is_vertical_scrollbar_disabled: false,
        });
        assert!(away < over && over < on_bar, "{away} {over} {on_bar}");
        assert!((on_bar - 1.0).abs() < 1e-6);
    }
}

#[cfg(test)]
#[path = "../option_sticky_tests.rs"]
mod option_sticky_tests;

#[cfg(test)]
#[path = "search_focus_tests.rs"]
mod search_focus_tests;