summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibGUI
diff options
context:
space:
mode:
authorthankyouverycool <66646555+thankyouverycool@users.noreply.github.com>2021-09-18 16:31:47 -0400
committerAndreas Kling <kling@serenityos.org>2021-09-19 00:21:37 +0200
commit46043b71cb6a7ea7c73232b4f3f8529f41b229b9 (patch)
tree45abb0314626ccac080eea2829a4201d61871311 /Userland/Libraries/LibGUI
parentaa06012249372447238c758ec7b67e86d8db6899 (diff)
downloadserenity-46043b71cb6a7ea7c73232b4f3f8529f41b229b9.zip
LibGUI: Add number_of_words() to TextEditors
Returns the total number of words in a document.
Diffstat (limited to 'Userland/Libraries/LibGUI')
-rw-r--r--Userland/Libraries/LibGUI/TextEditor.cpp23
-rw-r--r--Userland/Libraries/LibGUI/TextEditor.h1
2 files changed, 24 insertions, 0 deletions
diff --git a/Userland/Libraries/LibGUI/TextEditor.cpp b/Userland/Libraries/LibGUI/TextEditor.cpp
index ba97cfa2eb..b5ba783714 100644
--- a/Userland/Libraries/LibGUI/TextEditor.cpp
+++ b/Userland/Libraries/LibGUI/TextEditor.cpp
@@ -1335,6 +1335,29 @@ size_t TextEditor::number_of_selected_words() const
return word_count;
}
+size_t TextEditor::number_of_words() const
+{
+ if (document().is_empty())
+ return 0;
+
+ size_t word_count = 0;
+ bool in_word = false;
+ auto text = this->text();
+ for (char c : text) {
+ if (in_word && is_ascii_space(c)) {
+ in_word = false;
+ word_count++;
+ continue;
+ }
+ if (!in_word && !is_ascii_space(c))
+ in_word = true;
+ }
+ if (in_word)
+ word_count++;
+
+ return word_count;
+}
+
void TextEditor::delete_selection()
{
auto selection = normalized_selection();
diff --git a/Userland/Libraries/LibGUI/TextEditor.h b/Userland/Libraries/LibGUI/TextEditor.h
index 1e2059d6e0..a0ea51005e 100644
--- a/Userland/Libraries/LibGUI/TextEditor.h
+++ b/Userland/Libraries/LibGUI/TextEditor.h
@@ -126,6 +126,7 @@ public:
bool write_to_file_and_close(int fd);
bool has_selection() const { return m_selection.is_valid(); }
String selected_text() const;
+ size_t number_of_words() const;
size_t number_of_selected_words() const;
void set_selection(TextRange const&);
void clear_selection();