Skip to content

Commit ddae3d3

Browse files
pm100Copilot
andauthored
feat: add TextArea::clear() method (#15)
Adds a clear() method that empties the entire textarea content while integrating with the undo/redo history, so the content can be restored with undo(). Returns true if text was deleted, false if already empty. Ported from rhysd/tui-textarea#113. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 6d3f081 commit ddae3d3

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

src/textarea.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1299,6 +1299,37 @@ impl<'a> TextArea<'a> {
12991299
}
13001300
}
13011301

1302+
/// Clear the entire content of the textarea, leaving it empty. The cursor position before calling this method
1303+
/// does not affect the result. This method integrates with the undo/redo history, so the content can be restored
1304+
/// with [`TextArea::undo`]. Returns `true` if any text was deleted, `false` if the textarea was already empty.
1305+
///
1306+
/// ```
1307+
/// use ratatui_textarea::TextArea;
1308+
///
1309+
/// let mut textarea = TextArea::from(["hello", "world"]);
1310+
///
1311+
/// assert!(textarea.clear());
1312+
/// assert!(textarea.is_empty());
1313+
///
1314+
/// textarea.undo();
1315+
/// assert_eq!(textarea.lines(), ["hello", "world"]);
1316+
/// ```
1317+
pub fn clear(&mut self) -> bool {
1318+
if self.is_empty() {
1319+
return false;
1320+
}
1321+
// Count all chars plus newlines between lines.
1322+
let total = self
1323+
.lines()
1324+
.iter()
1325+
.map(|l| l.chars().count())
1326+
.sum::<usize>()
1327+
+ (self.lines().len() - 1);
1328+
self.move_cursor(CursorMove::Jump(0, 0));
1329+
self.delete_str(total);
1330+
true
1331+
}
1332+
13021333
/// Paste a string previously deleted by [`TextArea::delete_line_by_head`], [`TextArea::delete_line_by_end`],
13031334
/// [`TextArea::delete_word`], [`TextArea::delete_next_word`]. This method returns if some text was inserted or not
13041335
/// in the textarea.

tests/textarea.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1437,6 +1437,26 @@ fn test_delete_selection_before_insert() {
14371437
}
14381438
}
14391439

1440+
#[test]
1441+
fn test_clear_empty() {
1442+
let mut t = TextArea::default();
1443+
assert!(!t.clear(), "clear on empty textarea should return false");
1444+
assert!(t.is_empty());
1445+
}
1446+
1447+
#[test]
1448+
fn test_clear_with_undo_redo() {
1449+
let mut t = TextArea::from(["hello", "world"]);
1450+
assert!(t.clear());
1451+
assert!(t.is_empty());
1452+
1453+
t.undo();
1454+
assert_eq!(t.lines(), ["hello", "world"]);
1455+
1456+
t.redo();
1457+
assert!(t.is_empty());
1458+
}
1459+
14401460
#[test]
14411461
fn test_undo_redo_stop_selection() {
14421462
fn check(t: &mut TextArea, f: fn(&mut TextArea) -> bool) {

0 commit comments

Comments
 (0)