Skip to content

Commit 8146543

Browse files
ry-sevlinusg
authored andcommitted
LibGUI+TextEditor: Add the calculation of selected words
This moves the calculation of selected words that was originally in the TextEditor application to TextEditor in LibGUI. This allows all applications with text editors to get this number without having to calculating it themselves.
1 parent 074813e commit 8146543

File tree

3 files changed

+25
-13
lines changed

3 files changed

+25
-13
lines changed

Userland/Applications/TextEditor/MainWidget.cpp

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -765,20 +765,8 @@ void MainWidget::update_statusbar()
765765
builder.appendff("Line: {}, Column: {}", m_editor->cursor().line() + 1, m_editor->cursor().column());
766766

767767
if (m_editor->has_selection()) {
768-
int word_count = 0;
769-
bool in_word = false;
770768
String selected_text = m_editor->selected_text();
771-
for (char c : selected_text) {
772-
if (in_word && isspace(c)) {
773-
in_word = false;
774-
word_count++;
775-
continue;
776-
}
777-
if (!in_word && !isspace(c))
778-
in_word = true;
779-
}
780-
if (in_word)
781-
word_count++;
769+
auto word_count = m_editor->number_of_selected_words();
782770
builder.appendff(" Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
783771
}
784772
m_statusbar->set_text(builder.to_string());

Userland/Libraries/LibGUI/TextEditor.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,6 +1217,29 @@ String TextEditor::selected_text() const
12171217
return document().text_in_range(m_selection);
12181218
}
12191219

1220+
size_t TextEditor::number_of_selected_words() const
1221+
{
1222+
if (!has_selection())
1223+
return 0;
1224+
1225+
size_t word_count = 0;
1226+
bool in_word = false;
1227+
auto selected_text = this->selected_text();
1228+
for (char c : selected_text) {
1229+
if (in_word && isspace(c)) {
1230+
in_word = false;
1231+
word_count++;
1232+
continue;
1233+
}
1234+
if (!in_word && !isspace(c))
1235+
in_word = true;
1236+
}
1237+
if (in_word)
1238+
word_count++;
1239+
1240+
return word_count;
1241+
}
1242+
12201243
void TextEditor::delete_selection()
12211244
{
12221245
auto selection = normalized_selection();

Userland/Libraries/LibGUI/TextEditor.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ class TextEditor
115115
bool write_to_file(const String& path);
116116
bool has_selection() const { return m_selection.is_valid(); }
117117
String selected_text() const;
118+
size_t number_of_selected_words() const;
118119
void set_selection(const TextRange&);
119120
void clear_selection();
120121
bool can_undo() const { return document().can_undo(); }

0 commit comments

Comments
 (0)