Skip to content

Commit

Permalink
Add an API for customizing the return key in TextEdit (#4085)
Browse files Browse the repository at this point in the history
This PR allows customizing the return key in the TextEdit widget. Right
now, it's hard-coded to the Enter key, which is problematic in cases
when you want to use the Enter key for something else, and insert the
newline in a different way instead.
  • Loading branch information
lemon-sh authored Mar 25, 2024
1 parent 287a550 commit ab6c3f9
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions crates/egui/src/widgets/text_edit/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ pub struct TextEdit<'t> {
align: Align2,
clip_text: bool,
char_limit: usize,
return_key: KeyboardShortcut,
}

impl<'t> WidgetWithState for TextEdit<'t> {
Expand Down Expand Up @@ -107,7 +108,7 @@ impl<'t> TextEdit<'t> {
}
}

/// A [`TextEdit`] for multiple lines. Pressing enter key will create a new line.
/// A [`TextEdit`] for multiple lines. Pressing enter key will create a new line by default (can be changed with [`return_key`](TextEdit::return_key)).
pub fn multiline(text: &'t mut dyn TextBuffer) -> Self {
Self {
text,
Expand Down Expand Up @@ -136,6 +137,7 @@ impl<'t> TextEdit<'t> {
align: Align2::LEFT_TOP,
clip_text: false,
char_limit: usize::MAX,
return_key: KeyboardShortcut::new(Modifiers::NONE, Key::Enter),
}
}

Expand Down Expand Up @@ -348,6 +350,16 @@ impl<'t> TextEdit<'t> {
self.min_size = min_size;
self
}

/// Set the return key combination.
///
/// This combination will cause a newline on multiline,
/// whereas on singleline it will cause the widget to lose focus.
#[inline]
pub fn return_key(mut self, return_key: KeyboardShortcut) -> Self {
self.return_key = return_key;
self
}
}

// ----------------------------------------------------------------------------
Expand Down Expand Up @@ -453,6 +465,7 @@ impl<'t> TextEdit<'t> {
align,
clip_text,
char_limit,
return_key,
} = self;

let text_color = text_color
Expand Down Expand Up @@ -594,6 +607,7 @@ impl<'t> TextEdit<'t> {
default_cursor_range,
char_limit,
event_filter,
return_key,
);

if changed {
Expand Down Expand Up @@ -785,6 +799,7 @@ fn events(
default_cursor_range: CursorRange,
char_limit: usize,
event_filter: EventFilter,
return_key: KeyboardShortcut,
) -> (bool, CursorRange) {
let os = ui.ctx().os();

Expand Down Expand Up @@ -867,10 +882,13 @@ fn events(
Some(CCursorRange::one(ccursor))
}
Event::Key {
key: Key::Enter,
key,
pressed: true,
modifiers,
..
} => {
} if *key == return_key.logical_key
&& modifiers.matches_logically(return_key.modifiers) =>
{
if multiline {
let mut ccursor = text.delete_selected(&cursor_range);
text.insert_text_at(&mut ccursor, "\n", char_limit);
Expand Down

0 comments on commit ab6c3f9

Please sign in to comment.