-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTextUtils.cpp
More file actions
1379 lines (1130 loc) · 35.1 KB
/
TextUtils.cpp
File metadata and controls
1379 lines (1130 loc) · 35.1 KB
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
/*
* Copyright 2025, Johan Wagenheim <johan@dospuntos.no>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "TextUtils.h"
#include "Constants.h"
#include <Alert.h>
#include <Application.h>
#include <Catalog.h>
#include <File.h>
#include <LayoutBuilder.h>
#include <String.h>
#include <TextControl.h>
#include <algorithm>
#include <cctype>
#include <map>
#include <set>
#include <sstream>
#include <unicode/brkiter.h>
#include <unicode/coll.h>
#include <unicode/locid.h>
#include <unicode/unistr.h>
#include <vector>
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Text utilities"
int32 startSelection, endSelection; // For cursor position
int32 selStart, selEnd; // For selected text
bool appliedToSelection = true;
BString
GetText(BTextView* textView, bool isLineBased)
{
selStart = 0;
selEnd = 0;
if (textView == nullptr)
return BString("");
int32 textLength = textView->TextLength();
if (textLength == 0)
return BString("");
textView->GetSelection(&selStart, &selEnd);
if (selStart == selEnd) { // No selection
selStart = 0;
selEnd = textLength;
appliedToSelection = false;
} else if (isLineBased) {
const char* fullText = textView->Text();
// Extend selStartOut to beginning of line
while (selStart > 0 && fullText[selStart - 1] != '\n')
selStart--;
// Extend selEndOut to end of line (but don’t go past final \n)
while (selEnd < textLength && fullText[selEnd] != '\n')
selEnd++;
// Don't add one unless we're not already at a linebreak
if (selEnd < textLength && fullText[selEnd] == '\n')
selEnd++;
}
char* buffer = new char[selEnd - selStart + 1];
textView->GetText(selStart, selEnd - selStart, buffer);
buffer[selEnd - selStart] = '\0';
BString result(buffer);
delete[] buffer;
SaveCursorPosition(textView);
return result;
}
void
SaveCursorPosition(BTextView* textView)
{
textView->GetSelection(&startSelection, &endSelection);
}
void
RestoreCursorPosition(BTextView* textView)
{
textView->Select(startSelection, endSelection);
}
void
RestoreCursorPosition(BTextView* textView, int32 textLength)
{
textView->Select(selStart, selStart + textLength);
}
void
ConvertToUppercase(BTextView* textView)
{
BString text = GetText(textView, false);
BString original = text;
icu::UnicodeString unicodeText = icu::UnicodeString::fromUTF8(text.String());
unicodeText.toUpper();
// Convert back to UTF-8
std::string utf8Text;
unicodeText.toUTF8String(utf8Text);
text = utf8Text.c_str();
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text, text.Length());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("%i characters changed to uppercase in selection"),
changedCount);
} else {
status.SetToFormat(B_TRANSLATE("%i characters changed to uppercase in entire text"),
changedCount);
}
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
ConvertToLowercase(BTextView* textView)
{
BString text = GetText(textView, false);
BString original = text;
icu::UnicodeString unicodeText = icu::UnicodeString::fromUTF8(text.String());
unicodeText.toLower();
// Convert back to UTF-8
std::string utf8Text;
unicodeText.toUTF8String(utf8Text);
text = utf8Text.c_str();
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text, text.Length());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("%i characters changed to lowercase in selection"),
changedCount);
} else {
status.SetToFormat(B_TRANSLATE("%i characters changed to lowercase in entire text"),
changedCount);
}
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
ConvertToTitlecase(BTextView* textView)
{
BString text = GetText(textView, false);
BString original = text;
icu::UnicodeString unicodeText = icu::UnicodeString::fromUTF8(text.String());
unicodeText.toLower(); // normalize first
bool capitalizeNext = true;
for (int32_t i = 0; i < unicodeText.length(); ++i) {
UChar32 c = unicodeText.char32At(i);
if (u_isUWhiteSpace(c) || u_ispunct(c)) {
capitalizeNext = true;
continue;
}
if (capitalizeNext) {
UChar32 upperC = u_toupper(c);
unicodeText.replace(i, U16_LENGTH(c), upperC);
capitalizeNext = false;
}
}
std::string utf8Text;
unicodeText.toUTF8String(utf8Text);
text = utf8Text.c_str();
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text, text.Length());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i characters changed in selection"), changedCount);
else
status.SetToFormat(B_TRANSLATE("%i characters changed in entire text"), changedCount);
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
Capitalize(BTextView* textView)
{
BString rawText = GetText(textView, false);
BString original = rawText;
icu::UnicodeString utext = icu::UnicodeString::fromUTF8(rawText.String());
utext.toLower(); // lowercase everything first
bool capitalizeNext = true;
for (int32 i = 0; i < utext.length(); ++i) {
UChar32 c = utext.char32At(i);
if (capitalizeNext && u_isalpha(c)) {
UChar32 upper = u_totitle(c);
utext.replace(i, U16_LENGTH(c), upper);
capitalizeNext = false;
} else if (c == '.' || c == '!' || c == '?') {
capitalizeNext = true;
} else if (!u_isspace(c)) {
capitalizeNext = false;
}
}
// Convert result back to UTF-8
std::string utf8Result;
utext.toUTF8String(utf8Result);
BString text(utf8Result.c_str());
textView->Select(selStart, selEnd);
textView->Delete();
textView->Insert(text.String());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i characters changed in selection"), changedCount);
else
status.SetToFormat(B_TRANSLATE("%i characters changed in entire text"), changedCount);
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
ConvertToRandomCase(BTextView* textView)
{
BString text = GetText(textView, false);
BString original = text;
srand(time(nullptr)); // Seed random number generator
for (int32 i = 0; i < text.Length(); ++i) {
char currentChar = text.ByteAt(i);
if (std::isalpha(currentChar)) {
if (rand() % 2 == 0)
currentChar = std::toupper(currentChar);
else
currentChar = std::tolower(currentChar);
text.SetByteAt(i, currentChar);
}
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text.String(), text.Length());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i characters changed in selection"), changedCount);
else
status.SetToFormat(B_TRANSLATE("%i characters changed in entire text"), changedCount);
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
ConvertToAlternatingCase(BTextView* textView)
{
BString text = GetText(textView, false);
BString original = text;
bool uppercase = !(std::isupper(text.ByteAt(0)));
for (int32 i = 0; i < text.Length(); ++i) {
char currentChar = text.ByteAt(i);
if (std::isalpha(currentChar)) {
if (uppercase)
currentChar = std::toupper(currentChar);
else
currentChar = std::tolower(currentChar);
uppercase = !uppercase;
text.SetByteAt(i, currentChar);
}
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text.String(), text.Length());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i characters changed in selection"), changedCount);
else
status.SetToFormat(B_TRANSLATE("%i characters changed in entire text"), changedCount);
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
ToggleCase(BTextView* textView)
{
BString text = GetText(textView, false);
BString original = text;
for (int32 i = 0; i < text.Length(); ++i) {
char currentChar = text.ByteAt(i);
if (std::isupper(currentChar))
currentChar = std::tolower(currentChar);
else if (std::islower(currentChar))
currentChar = std::toupper(currentChar);
text.SetByteAt(i, currentChar);
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text.String(), text.Length());
BString status;
int32 changedCount = _CountCharChanges(original, text);
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i characters changed in selection"), changedCount);
else
status.SetToFormat(B_TRANSLATE("%i characters changed in entire text"), changedCount);
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
RemoveLineBreaks(BTextView* textView, BString replacement)
{
BString text = GetText(textView, true);
int32 count = 0;
for (int32 i = 0; i < text.Length(); i++) {
if (text[i] == '\n')
count++;
}
text.ReplaceAll("\n", replacement);
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text.String(), text.Length());
BString status;
if (replacement.IsEmpty()) {
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i line breaks removed in selection"), count);
else
status.SetToFormat(B_TRANSLATE("%i line breaks removed in entire text"), count);
} else {
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("%i line breaks replaced in selection"), count);
else
status.SetToFormat(B_TRANSLATE("%i line breaks replaced in entire text"), count);
}
SendStatusMessage(status);
RestoreCursorPosition(textView, text.Length());
}
// Note: The ROT-13 algorithm is symmetrical, the same function will encode and decode the text.
void
ConvertToROT13(BTextView* textView)
{
BString text = GetText(textView, false);
int32 count = 0;
for (int32 i = 0; i < text.Length(); ++i) {
char currentChar = text.ByteAt(i);
if (std::isalpha(currentChar)) {
if (std::islower(currentChar))
currentChar = 'a' + (currentChar - 'a' + 13) % 26;
else
currentChar = 'A' + (currentChar - 'A' + 13) % 26;
count++;
}
text.SetByteAt(i, currentChar);
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text.String(), text.Length());
BString status;
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("ROT13 applied to %i characters in selection"), count);
else
status.SetToFormat(B_TRANSLATE("ROT13 applied to %i characters in entire text"), count);
SendStatusMessage(status);
RestoreCursorPosition(textView);
}
void
URLEncode(BTextView* textView)
{
BString text = GetText(textView, false);
BString encoded;
for (int32 i = 0; i < text.Length(); ++i) {
char currentChar = text.ByteAt(i);
// Check if the character is URL-safe (alphanumeric or special characters)
if (std::isalnum(currentChar) || currentChar == '-' || currentChar == '_'
|| currentChar == '.' || currentChar == '~') {
encoded += currentChar;
} else {
// Encode the non-safe characters
encoded += '%';
std::stringstream ss;
ss << std::uppercase << std::hex
<< (int)(unsigned char)currentChar; // Convert char to hex
std::string hexStr = ss.str();
// Ensure the hex string is two characters long
if (hexStr.length() == 1)
encoded += '0'; // Add leading zero if needed
encoded += BString(hexStr.c_str()); // Convert std::string to BString and append
}
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, encoded.String(), encoded.Length());
BString status;
if (appliedToSelection)
status.Append(B_TRANSLATE("Selected text URL-encoded"));
else
status.Append(B_TRANSLATE("Entire text URL-encoded"));
SendStatusMessage(status);
RestoreCursorPosition(textView, encoded.Length());
}
void
URLDecode(BTextView* textView)
{
BString text = GetText(textView, false);
BString decoded;
for (int32 i = 0; i < text.Length(); ++i) {
char currentChar = text.ByteAt(i);
if (currentChar == '%') {
// Check if there are enough characters for a valid hex code
if (i + 2 < text.Length()) {
char hex[3] = {text.ByteAt(i + 1), text.ByteAt(i + 2), '\0'};
int decodedChar = 0;
std::stringstream ss;
ss << std::hex << hex;
ss >> decodedChar;
// Append the decoded character
decoded += static_cast<char>(decodedChar);
i += 2; // Skip the next two characters (hex code)
}
} else {
// Regular character, append to decoded string
decoded += currentChar;
}
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, decoded.String(), decoded.Length());
BString status;
if (appliedToSelection)
status.Append(B_TRANSLATE("Selected text URL-decoded"));
else
status.Append(B_TRANSLATE("Entire text URL-decoded"));
SendStatusMessage(status);
RestoreCursorPosition(textView, decoded.Length());
}
void
AddStringsToEachLine(BTextView* textView, const BString& startString, const BString& endString)
{
BString text = GetText(textView, true);
int32 lineCount = 0;
BString updatedText;
int32 start = 0;
int32 end;
// Process each line
while ((end = text.FindFirst('\n', start)) >= 0) {
BString line(text.String() + start, end - start);
updatedText << startString << line << endString << '\n';
start = end + 1; // Move past the line break
lineCount++;
}
// Last line (if it doesn't end with '\n')
if (start < text.Length()) {
BString line(text.String() + start, text.Length() - start);
updatedText << startString << line << endString;
lineCount++;
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString status;
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("Prefix/suffix added to %i lines in selection"), lineCount);
} else {
status.SetToFormat(B_TRANSLATE("Prefix/suffix added to %i lines in entire text"),
lineCount);
}
SendStatusMessage(status);
RestoreCursorPosition(textView, updatedText.Length());
}
void
RemoveStringsFromEachLine(BTextView* textView, const BString& prefix, const BString& suffix)
{
BString text = GetText(textView, true);
BString updatedText;
int32 start = 0;
int32 end;
int32 lineCount = 0;
while ((end = text.FindFirst('\n', start)) >= 0) {
BString line(text.String() + start, end - start);
// Remove prefix if present
if (!prefix.IsEmpty() && line.StartsWith(prefix))
line.Remove(0, prefix.Length());
// Remove suffix if present
if (!suffix.IsEmpty() && line.EndsWith(suffix))
line.Truncate(line.Length() - suffix.Length());
updatedText << line << '\n';
start = end + 1;
lineCount++;
}
// Handle last line if it doesn't end with \n
if (start < text.Length()) {
BString line(text.String() + start, text.Length() - start);
if (!prefix.IsEmpty() && line.StartsWith(prefix))
line.Remove(0, prefix.Length());
if (!suffix.IsEmpty() && line.EndsWith(suffix))
line.Truncate(line.Length() - suffix.Length());
updatedText << line;
lineCount++;
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString status;
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("Prefix/suffix removed from %i lines in selection"),
lineCount);
} else {
status.SetToFormat(B_TRANSLATE("Prefix/suffix removed from %i lines in entire text"),
lineCount);
}
SendStatusMessage(status);
RestoreCursorPosition(textView, updatedText.Length());
}
void
InsertLineBreaks(BTextView* textView, int32 maxLength, bool breakOnWords)
{
bool appliedToSelection = false;
BString text = GetText(textView, true);
BString updatedText;
int32 lineStart = 0;
while (lineStart < text.Length()) {
// Find the end of the current line
int32 lineEnd = text.FindFirst('\n', lineStart);
bool isLastLine = false;
if (lineEnd == B_ERROR) {
lineEnd = text.Length();
isLastLine = true;
}
BString line;
text.CopyInto(line, lineStart, lineEnd - lineStart);
// Process line if needed
int32 pos = 0;
while (pos < line.Length()) {
int32 segmentEnd = pos + maxLength;
if (segmentEnd >= line.Length()) {
updatedText.Append(line.String() + pos, line.Length() - pos);
break;
}
if (breakOnWords) {
int32 nearestSpace = line.FindLast(' ', segmentEnd);
if (nearestSpace >= pos)
segmentEnd = nearestSpace;
else
segmentEnd = pos + maxLength;
}
updatedText.Append(line.String() + pos, segmentEnd - pos);
updatedText.Append("\n");
if (segmentEnd < line.Length() && line[segmentEnd] == ' ')
pos = segmentEnd + 1; // skip space
else
pos = segmentEnd;
}
// If line was already short and unbroken, add newline
if (line.Length() <= maxLength)
updatedText.Append("\n");
lineStart = lineEnd + 1;
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString status;
BString breakType
= breakOnWords ? B_TRANSLATE("breaking on words") : B_TRANSLATE("breaking anywhere");
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("Line breaks inserted in selection (max length: %d, %s)"),
maxLength, breakType.String());
} else {
status.SetToFormat(B_TRANSLATE("Line breaks inserted in entire text (max length: %d, %s)"),
maxLength, breakType.String());
}
SendStatusMessage(status);
RestoreCursorPosition(textView, updatedText.Length());
}
void
BreakLinesOnDelimiter(BTextView* textView, const BString& delimiter, bool keepDelimiter)
{
BString text = GetText(textView, true);
BString updatedText;
int32 start = 0;
int32 delimiterPosition;
while ((delimiterPosition = text.FindFirst(delimiter, start)) >= 0) {
if (keepDelimiter) {
// Include the delimiter in the line
updatedText.Append(text.String() + start,
delimiterPosition - start + delimiter.Length());
} else {
// Exclude the delimiter from the line
updatedText.Append(text.String() + start, delimiterPosition - start);
}
updatedText.Append("\n");
start = delimiterPosition + delimiter.Length();
}
if (start < text.Length())
updatedText.Append(text.String() + start, text.Length() - start);
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString status;
BString keepStr = keepDelimiter ? B_TRANSLATE("kept") : B_TRANSLATE("removed");
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("Lines broken on delimiter \"%s\" (%s) in selection"),
delimiter.String(), keepStr.String());
} else {
status.SetToFormat(B_TRANSLATE("Lines broken on delimiter \"%s\" (%s) in entire text"),
delimiter.String(), keepStr.String());
}
SendStatusMessage(status);
RestoreCursorPosition(textView, updatedText.Length());
}
void
TrimWhitespace(BTextView* textView)
{
BString text = GetText(textView, true);
BString updatedText;
int32 start = 0;
int32 end;
while ((end = text.FindFirst('\n', start)) >= 0) {
BString line(text.String() + start, end - start);
line.Trim();
updatedText << line << "\n";
start = end + 1;
}
if (start < text.Length()) {
BString line(text.String() + start, text.Length() - start);
line.Trim();
updatedText << line << "\n";
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString status;
if (appliedToSelection)
status.SetToFormat(B_TRANSLATE("Whitespace trimmed from lines in selection"));
else
status.SetToFormat(B_TRANSLATE("Whitespace trimmed from lines in entire text"));
SendStatusMessage(status);
RestoreCursorPosition(textView, updatedText.Length());
}
void
TrimEmptyLines(BTextView* textView)
{
BString text = GetText(textView, true);
int32 start = 0;
int32 end;
int32 removedLineCount = 0;
BString updatedText;
while ((end = text.FindFirst('\n', start)) >= 0) {
BString line(text.String() + start, end - start);
if (line.Length() > 0)
updatedText << line << '\n';
else
removedLineCount++;
start = end + 1;
}
// Handle last line if no '\n'
if (start < text.Length()) {
BString lastLine(text.String() + start, text.Length() - start);
if (lastLine.Length() > 0)
updatedText.Append(lastLine);
else
removedLineCount++;
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString status;
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("%d empty lines removed from selection"), removedLineCount);
} else {
status.SetToFormat(B_TRANSLATE("%d empty lines removed from entire text"),
removedLineCount);
}
SendStatusMessage(status);
RestoreCursorPosition(textView, updatedText.Length());
}
bool
IsFullWord(const BString& text, int32 pos, int32 length)
{
bool startOk = (pos == 0) || !isalnum(text.ByteAt(pos - 1));
bool endOk = (pos + length >= text.Length() || !isalnum(text.ByteAt(pos + length)));
return startOk && endOk;
}
void
ReplaceAll(BTextView* textView, BString find, BString replaceWith, bool caseSensitive,
bool fullWordsOnly)
{
BString text = GetText(textView, false);
int32 replacementCount = 0;
if (find.IsEmpty())
return;
int32 pos = 0;
int32 findLength = find.Length();
while (true) {
pos = caseSensitive ? text.FindFirst(find.String(), pos)
: text.IFindFirst(find.String(), pos);
if (pos < 0)
break;
if (fullWordsOnly && !IsFullWord(text, pos, findLength)) {
pos += findLength;
continue;
}
text.Remove(pos, findLength);
text.Insert(replaceWith, pos);
pos += replaceWith.Length();
replacementCount++;
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, text.String(), text.Length());
BString status;
if (appliedToSelection) {
status.SetToFormat(B_TRANSLATE("%d occurrences of \"%s\" replaced in selection"),
replacementCount, find.String());
} else {
status.SetToFormat(B_TRANSLATE("%d occurrences of \"%s\" replaced in entire text"),
replacementCount, find.String());
}
SendStatusMessage(status);
RestoreCursorPosition(textView, text.Length());
}
void
SortLines(BTextView* textView, bool ascending, bool caseSensitive)
{
BString text = GetText(textView, true);
// Split text into lines
std::vector<BString> lines;
int32_t start = 0;
while (true) {
int32_t end = text.FindFirst('\n', start);
BString line;
if (end >= 0) {
text.CopyInto(line, start, end - start);
start = end + 1;
} else {
text.CopyInto(line, start, text.Length() - start);
lines.push_back(line);
break;
}
lines.push_back(line);
}
// Create ICU Collator
UErrorCode status = U_ZERO_ERROR;
std::unique_ptr<icu::Collator> collator(
icu::Collator::createInstance(icu::Locale::getDefault(), status));
collator->setStrength(
caseSensitive ? icu::Collator::TERTIARY // case-sensitive, accent-sensitive
: icu::Collator::SECONDARY // case-insensitive, accent-sensitive
);
// Sort using ICU
std::sort(lines.begin(), lines.end(), [&](const BString& a, const BString& b) {
icu::UnicodeString ua = icu::UnicodeString::fromUTF8(a.String());
icu::UnicodeString ub = icu::UnicodeString::fromUTF8(b.String());
UErrorCode cmpStatus = U_ZERO_ERROR;
UCollationResult result = collator->compare(ua, ub, cmpStatus);
if (U_FAILURE(cmpStatus))
return ascending; // fallback: don't swap
return ascending ? result == UCOL_LESS : result == UCOL_GREATER;
});
// Reconstruct the sorted text
BString updatedText;
for (size_t i = 0; i < lines.size(); ++i) {
updatedText << lines[i];
if (i != lines.size() - 1)
updatedText << '\n';
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString order = ascending ? B_TRANSLATE("ascending") : B_TRANSLATE("descending");
BString statusMsg;
if (appliedToSelection) {
statusMsg.SetToFormat(
B_TRANSLATE("%zu lines sorted alphabetically in %s order in selection"), lines.size(),
order.String());
} else {
statusMsg.SetToFormat(
B_TRANSLATE("%zu lines sorted alphabetically in %s order in entire text"), lines.size(),
order.String());
}
SendStatusMessage(statusMsg);
RestoreCursorPosition(textView, updatedText.Length());
}
void
SortLinesByLength(BTextView* textView, bool ascending, bool caseSensitive)
{
BString text = GetText(textView, true);
// Split text into lines
std::vector<BString> lines;
int32_t start = 0;
while (true) {
int32_t end = text.FindFirst('\n', start);
BString line;
if (end >= 0) {
text.CopyInto(line, start, end - start);
start = end + 1;
} else {
text.CopyInto(line, start, text.Length() - start);
lines.push_back(line);
break;
}
lines.push_back(line);
}
// Sort by length, with optional case-aware tiebreaker
std::sort(lines.begin(), lines.end(), [&](const BString& a, const BString& b) {
int32_t lenA = a.Length();
int32_t lenB = b.Length();
if (lenA != lenB)
return ascending ? (lenA < lenB) : (lenA > lenB);
// Tie-breaker: case-sensitive or insensitive compare
icu::UnicodeString ua = icu::UnicodeString::fromUTF8(a.String());
icu::UnicodeString ub = icu::UnicodeString::fromUTF8(b.String());
if (!caseSensitive) {
ua.toLower();
ub.toLower();
}
int cmp = ua.compare(ub);
return ascending ? (cmp < 0) : (cmp > 0);
});
// Reconstruct sorted text
BString updatedText;
for (size_t i = 0; i < lines.size(); ++i) {
updatedText << lines[i];
if (i != lines.size() - 1)
updatedText << '\n';
}
textView->Delete(selStart, selEnd);
textView->Insert(selStart, updatedText.String(), updatedText.Length());
BString order = ascending ? B_TRANSLATE("ascending") : B_TRANSLATE("descending");
BString statusMsg;
if (appliedToSelection) {
statusMsg.SetToFormat(
B_TRANSLATE("%zu lines sorted by line length in %s order in selection"), lines.size(),
order.String());
} else {
statusMsg.SetToFormat(
B_TRANSLATE("%zu lines sorted by line length in %s order in entire text"), lines.size(),
order.String());
}
SendStatusMessage(statusMsg);
RestoreCursorPosition(textView, updatedText.Length());
}
void
RemoveDuplicateLines(BTextView* textView, bool caseSensitive)
{
BString text = GetText(textView, true);
// Split text into lines
std::vector<BString> lines;
int32_t start = 0;
while (true) {
int32_t end = text.FindFirst('\n', start);
BString line;
if (end >= 0) {
text.CopyInto(line, start, end - start);
start = end + 1;
} else {
text.CopyInto(line, start, text.Length() - start);
lines.push_back(line);
break;
}
lines.push_back(line);
}
// Store seen lines using ICU UnicodeString for proper comparison
std::set<icu::UnicodeString> seen;