forked from rizonesoft/Notepad3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEdit.c
9642 lines (8104 loc) · 338 KB
/
Edit.c
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
// encoding: UTF-8
/******************************************************************************
* *
* *
* Notepad3 *
* *
* Edit.c *
* Text File Editing Helper Stuff *
* Based on code from Notepad2, (c) Florian Balmer 1996-2011 *
* *
* (c) Rizonesoft 2008-2022 *
* https://rizonesoft.com *
* *
* *
*******************************************************************************/
#include "Helpers.h"
#include <shlwapi.h>
#include <commctrl.h>
#include <commdlg.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <shellapi.h>
#include <time.h>
#include "Styles.h"
#include "Dialogs.h"
#include "crypto/crypto.h"
#include "uthash/utarray.h"
#include "uthash/utlist.h"
#include "tinyexpr/tinyexpr.h"
#include "Encoding.h"
#include "MuiLanguage.h"
#include "Notepad3.h"
#include "Config/Config.h"
#include "DarkMode/DarkMode.h"
#include "SciCall.h"
#include "Edit.h"
#ifndef LCMAP_TITLECASE
#define LCMAP_TITLECASE 0x00000300 // Title Case Letters bit mask
#endif
static bool s_bSwitchedFindReplace = false;
static int s_xFindReplaceDlgSave;
static int s_yFindReplaceDlgSave;
static char DelimChars[ANSI_CHAR_BUFFER] = { '\0' };
static char DelimCharsAccel[ANSI_CHAR_BUFFER] = { '\0' };
static char WordCharsDefault[ANSI_CHAR_BUFFER] = { '\0' };
static char WhiteSpaceCharsDefault[ANSI_CHAR_BUFFER] = { '\0' };
static char PunctuationCharsDefault[ANSI_CHAR_BUFFER] = { '\0' };
static char WordCharsAccelerated[ANSI_CHAR_BUFFER] = { '\0' };
static char WhiteSpaceCharsAccelerated[ANSI_CHAR_BUFFER] = { '\0' };
static char PunctuationCharsAccelerated[1] = { '\0' }; // empty!
static WCHAR W_DelimChars[ANSI_CHAR_BUFFER] = { L'\0' };
static WCHAR W_DelimCharsAccel[ANSI_CHAR_BUFFER] = { L'\0' };
static WCHAR W_WhiteSpaceCharsDefault[ANSI_CHAR_BUFFER] = { L'\0' };
static WCHAR W_WhiteSpaceCharsAccelerated[ANSI_CHAR_BUFFER] = { L'\0' };
static char AutoCompleteFillUpChars[64] = { '\0' };
static bool s_ACFillUpCharsHaveNewLn = false;
// Default Codepage and Character Set
#define W_AUTOC_WORD_ANSI1252 L"#$%&@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ"
static char AutoCompleteWordCharSet[ANSI_CHAR_BUFFER] = { L'\0' };
// Is the character a white space char?
#define IsWhiteSpace(ch) StrChrA(WhiteSpaceCharsDefault, (ch))
#define IsAccelWhiteSpace(ch) StrChrA(WhiteSpaceCharsAccelerated, (ch))
#define IsWhiteSpaceW(wch) StrChrW(W_WhiteSpaceCharsDefault, (wch))
#define IsAccelWhiteSpaceW(wch) StrChrW(W_WhiteSpaceCharsAccelerated, (wch))
static LPCWSTR const s_pColorRegEx = L"#([0-9a-fA-F]){8}|#([0-9a-fA-F]){6}"; // ARGB, RGBA, RGB
static LPCWSTR const s_pColorRegEx_Tr = L"#([0-9a-fA-F]){8}"; // no RGB search (BGRA)
static LPCWSTR const s_pUnicodeRegEx = L"(\\\\[uU|xX]([0-9a-fA-F]){4}|\\\\[xX]([0-9a-fA-F]){2})+";
// https://mathiasbynens.be/demo/url-regex : @stephenhay
//#define HYPLNK_REGEX_FULL L"\\b(?:(?:https?|ftp|file)://|www\\.|ftp\\.)[^\\s/$.?#].[^\\s]*"
// using Gruber's Liberal Regex Pattern for All URLs (https://gist.github.com/gruber/249502)
/// => unfortunately to slow to use as scanner
//#define HYPLNK_REGEX_FULL L"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)"\
// L"(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+"\
// L"(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))"
// --- pretty fast ---
// https://www.regular-expressions.info/unicode.html
// \p{L} : any kind of letter from any language
// \p{N} : any kind of numeric character in any script
// \p{S} : math symbols, currency signs, dingbats, box-drawing characters, etc.
//#define HYPLNK_REGEX_VALID_CDPT L"a-zA-Z0-9\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF+&@#/%=~_|$"
#define HYPLNK_REGEX_VALID_CDPT "\\p{L}\\p{N}\\p{Sc}\\p{So}\\*\\[\\];^°+§&@#/%=~_|'"
#define HYPLNK_REGEX_FULL "\\b(?:(?:https?|ftp|file)://|www\\.|ftp\\.)"\
"(?:\\([-" HYPLNK_REGEX_VALID_CDPT "?!:,.]*\\)|[-" HYPLNK_REGEX_VALID_CDPT "?!:,.])*"\
"(?:\\([-" HYPLNK_REGEX_VALID_CDPT "?!:,.]*\\)|[-" HYPLNK_REGEX_VALID_CDPT "])"
static LPCSTR const s_pUrlRegExA = HYPLNK_REGEX_FULL;
static LPCWSTR const s_pUrlRegEx = _W(HYPLNK_REGEX_FULL);
// ----------------------------------------------------------------------------
enum AlignMask {
ALIGN_LEFT = 0,
ALIGN_RIGHT = 1,
ALIGN_CENTER = 2,
ALIGN_JUSTIFY = 3,
ALIGN_JUSTIFY_EX = 4
};
enum SortOrderMask {
SORT_ASCENDING = 0x001,
SORT_DESCENDING = 0x002,
SORT_SHUFFLE = 0x004,
SORT_MERGEDUP = 0x008,
SORT_UNIQDUP = 0x010,
SORT_UNIQUNIQ = 0x020,
SORT_REMZEROLEN = 0x040,
SORT_REMWSPACELN = 0x080,
SORT_NOCASE = 0x100,
SORT_LOGICAL = 0x200,
SORT_LEXICOGRAPH = 0x400,
SORT_COLUMN = 0x800
};
//=============================================================================
//
// Delay Message Queue Handling (TODO: MultiThreading)
//
static CmdMessageQueue_t* MessageQueue = NULL;
// ----------------------------------------------------------------------------
static int msgcmp(void* mqc1, void* mqc2)
{
const CmdMessageQueue_t* const pMQC1 = (CmdMessageQueue_t*)mqc1;
const CmdMessageQueue_t* const pMQC2 = (CmdMessageQueue_t*)mqc2;
if ((pMQC1->cmd == pMQC2->cmd)
&& (pMQC1->hwnd == pMQC2->hwnd)
&& (pMQC1->wparam == pMQC2->wparam)
&& (pMQC1->lparam == pMQC2->lparam)
) {
return 0;
}
return 1;
}
static int sortcmp(void *mqc1, void *mqc2) {
const CmdMessageQueue_t *const pMQC1 = (CmdMessageQueue_t *)mqc1;
const CmdMessageQueue_t *const pMQC2 = (CmdMessageQueue_t *)mqc2;
return (pMQC1->delay - pMQC2->delay);
}
// ----------------------------------------------------------------------------
#define _MQ_TIMER_CYCLE (USER_TIMER_MINIMUM << 1)
#define _MQ_ms2cycl(T) (((T) + USER_TIMER_MINIMUM) / _MQ_TIMER_CYCLE)
#define _MQ_STD (_MQ_TIMER_CYCLE << 2)
static void _MQ_AppendCmd(CmdMessageQueue_t* const pMsgQCmd, int cycles)
{
if (!pMsgQCmd) { return; }
cycles = clampi(cycles, 0, _MQ_ms2cycl(60000));
CmdMessageQueue_t* pmqc = NULL;
DL_SEARCH(MessageQueue, pmqc, pMsgQCmd, msgcmp);
if (!pmqc) { // NOT found, create new one
pmqc = AllocMem(sizeof(CmdMessageQueue_t), HEAP_ZERO_MEMORY);
if (pmqc) {
*pmqc = *pMsgQCmd;
pmqc->delay = cycles;
DL_APPEND(MessageQueue, pmqc);
}
} else {
if ((pmqc->delay > 0) && (cycles > 0)) {
pmqc->delay = (pmqc->delay + cycles) >> 1; // median delay
} else {
pmqc->delay = cycles;
}
}
if (0 == cycles) {
PostMessage(pMsgQCmd->hwnd, pMsgQCmd->cmd, pMsgQCmd->wparam, pMsgQCmd->lparam);
}
//~DL_SORT(MessageQueue, sortcmp); // next scheduled first
}
// ----------------------------------------------------------------------------
/* not used yet
static void _MQ_DropAll() {
CmdMessageQueue_t *pmqc = NULL;
DL_FOREACH(MessageQueue, pmqc) {
pmqc->delay = -1;
}
}
*/
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// called by MarkAll Timer
//
static void CALLBACK MQ_ExecuteNext(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
UNREFERENCED_PARAMETER(hwnd); // must be main wnd
UNREFERENCED_PARAMETER(uMsg); // must be WM_TIMER
UNREFERENCED_PARAMETER(idEvent); // must be pTimerIdentifier
UNREFERENCED_PARAMETER(dwTime); // This is the value returned by the GetTickCount function
CmdMessageQueue_t *pmqc;
DL_FOREACH(MessageQueue, pmqc) {
if (pmqc->delay >= 0) {
--(pmqc->delay);
}
if (pmqc->delay == 0) {
if (IsWindow(pmqc->hwnd)) {
PostMessage(pmqc->hwnd, pmqc->cmd, pmqc->wparam, pmqc->lparam);
}
}
}
}
//=============================================================================
//
// EditReplaceSelection()
//
void DuplicateEFR(LPEDITFINDREPLACE dst, CLPCEDITFINDREPLACE src)
{
dst->fuFlags = src->fuFlags;
dst->bTransformBS = src->bTransformBS;
dst->bFindClose = src->bFindClose;
dst->bReplaceClose = src->bReplaceClose;
dst->bNoFindWrap = src->bNoFindWrap;
dst->bRegExprSearch = src->bRegExprSearch;
dst->bWildcardSearch = src->bWildcardSearch;
dst->bMarkOccurences = src->bMarkOccurences;
dst->bHideNonMatchedLines = src->bHideNonMatchedLines;
dst->bStateChanged = src->bStateChanged;
dst->hwnd = src->hwnd;
if (!(dst->chFindPattern)) {
dst->chFindPattern = StrgCreate(StrgGet(src->chFindPattern));
}
else {
StrgReset(dst->chFindPattern, StrgGet(src->chFindPattern));
}
if (!(dst->chReplaceTemplate)) {
dst->chReplaceTemplate = StrgCreate(StrgGet(src->chReplaceTemplate));
}
else {
StrgReset(dst->chReplaceTemplate, StrgGet(src->chReplaceTemplate));
}
}
void ReleaseEFR(LPEDITFINDREPLACE efr)
{
StrgDestroy(efr->chFindPattern);
efr->chFindPattern = NULL;
StrgDestroy(efr->chReplaceTemplate);
efr->chReplaceTemplate = NULL;
}
// --------------------------------------------------------------------------
//=============================================================================
//
// EditReplaceSelection()
//
void EditReplaceSelection(const char* text, bool bForceSel)
{
UndoTransActionBegin();
bool const bSelWasEmpty = SciCall_IsSelectionEmpty();
DocPos const posSelBeg = SciCall_GetSelectionStart();
SciCall_ReplaceSel(text);
if (bForceSel || !bSelWasEmpty) {
SciCall_SetSel(posSelBeg, SciCall_GetCurrentPos());
}
EndUndoTransAction();
}
//=============================================================================
//
// EditSetWordDelimiter()
//
void EditInitWordDelimiter(HWND hwnd)
{
UNREFERENCED_PARAMETER(hwnd);
ZeroMemory(WordCharsDefault, COUNTOF(WordCharsDefault));
ZeroMemory(WhiteSpaceCharsDefault, COUNTOF(WhiteSpaceCharsDefault));
ZeroMemory(PunctuationCharsDefault, COUNTOF(PunctuationCharsDefault));
ZeroMemory(WordCharsAccelerated, COUNTOF(WordCharsAccelerated));
ZeroMemory(WhiteSpaceCharsAccelerated, COUNTOF(WhiteSpaceCharsAccelerated));
//ZeroMemory(PunctuationCharsAccelerated, COUNTOF(PunctuationCharsAccelerated)); // empty!
// 1st get/set defaults
SciCall_GetWordChars(WordCharsDefault);
SciCall_GetWhiteSpaceChars(WhiteSpaceCharsDefault);
SciCall_GetPunctuationChars(PunctuationCharsDefault);
// default word delimiter chars are whitespace & punctuation & line ends
const char* lineEnds = "\r\n";
StringCchCopyA(DelimChars, COUNTOF(DelimChars), WhiteSpaceCharsDefault);
StringCchCatA(DelimChars, COUNTOF(DelimChars), PunctuationCharsDefault);
StringCchCatA(DelimChars, COUNTOF(DelimChars), lineEnds);
// 2nd get user settings
char whitesp[ANSI_CHAR_BUFFER*2] = { '\0' };
if (StrIsNotEmpty(Settings2.ExtendedWhiteSpaceChars)) {
WideCharToMultiByte(Encoding_SciCP, 0, Settings2.ExtendedWhiteSpaceChars, -1, whitesp, (int)COUNTOF(whitesp), NULL, NULL);
}
// 3rd set accelerated arrays
// init with default
StringCchCopyA(WhiteSpaceCharsAccelerated, COUNTOF(WhiteSpaceCharsAccelerated), WhiteSpaceCharsDefault);
// add only 7-bit-ASCII chars to accelerated whitespace list
size_t const wsplen = StringCchLenA(whitesp, ANSI_CHAR_BUFFER);
for (size_t i = 0; i < wsplen; i++) {
if (whitesp[i] & 0x7F) {
if (!StrChrA(WhiteSpaceCharsAccelerated, whitesp[i])) {
StringCchCatNA(WhiteSpaceCharsAccelerated, COUNTOF(WhiteSpaceCharsAccelerated), &(whitesp[i]), 1);
}
}
}
// construct word char array
StringCchCopyA(WordCharsAccelerated, COUNTOF(WordCharsAccelerated), WordCharsDefault); // init
// add punctuation chars not listed in white-space array
size_t const pcdlen = StringCchLenA(PunctuationCharsDefault, ANSI_CHAR_BUFFER);
for (size_t i = 0; i < pcdlen; i++) {
if (!StrChrA(WhiteSpaceCharsAccelerated, PunctuationCharsDefault[i])) {
StringCchCatNA(WordCharsAccelerated, COUNTOF(WordCharsAccelerated), &(PunctuationCharsDefault[i]), 1);
}
}
// construct accelerated delimiters
StringCchCopyA(DelimCharsAccel, COUNTOF(DelimCharsAccel), WhiteSpaceCharsDefault);
StringCchCatA(DelimCharsAccel, COUNTOF(DelimCharsAccel), lineEnds);
if (StrIsNotEmpty(Settings2.AutoCompleteFillUpChars)) {
WideCharToMultiByte(Encoding_SciCP, 0, Settings2.AutoCompleteFillUpChars, -1, AutoCompleteFillUpChars, (int)COUNTOF(AutoCompleteFillUpChars), NULL, NULL);
UnSlashA(AutoCompleteFillUpChars, Encoding_SciCP);
s_ACFillUpCharsHaveNewLn = false;
int i = 0;
while (AutoCompleteFillUpChars[i]) {
if ((AutoCompleteFillUpChars[i] == '\r') || (AutoCompleteFillUpChars[i] == '\n')) {
s_ACFillUpCharsHaveNewLn = true;
break;
}
++i;
}
}
SciCall_AutoCSetFillups(AutoCompleteFillUpChars);
if (StrIsNotEmpty(Settings2.AutoCompleteWordCharSet)) {
WideCharToMultiByte(Encoding_SciCP, 0, Settings2.AutoCompleteWordCharSet, -1, AutoCompleteWordCharSet, (int)COUNTOF(AutoCompleteWordCharSet), NULL, NULL);
Globals.bUseLimitedAutoCCharSet = true;
} else {
WideCharToMultiByte(Encoding_SciCP, 0, W_AUTOC_WORD_ANSI1252, -1, AutoCompleteWordCharSet, (int)COUNTOF(AutoCompleteWordCharSet), NULL, NULL);
Globals.bUseLimitedAutoCCharSet = false;
}
// construct wide char arrays
MultiByteToWideChar(Encoding_SciCP, 0, DelimChars, -1, W_DelimChars, (int)COUNTOF(W_DelimChars));
MultiByteToWideChar(Encoding_SciCP, 0, DelimCharsAccel, -1, W_DelimCharsAccel, (int)COUNTOF(W_DelimCharsAccel));
MultiByteToWideChar(Encoding_SciCP, 0, WhiteSpaceCharsDefault, -1, W_WhiteSpaceCharsDefault, (int)COUNTOF(W_WhiteSpaceCharsDefault));
MultiByteToWideChar(Encoding_SciCP, 0, WhiteSpaceCharsAccelerated, -1, W_WhiteSpaceCharsAccelerated, (int)COUNTOF(W_WhiteSpaceCharsAccelerated));
}
//=============================================================================
//
// EditSetNewText()
//
extern bool s_bFreezeAppTitle;
void EditSetNewText(HWND hwnd, const char* lpstrText, DocPosU lenText, bool bClearUndoHistory)
{
if (!lpstrText) {
lenText = 0;
}
s_bFreezeAppTitle = true;
// clear markers, flags and positions
if (FocusedView.HideNonMatchedLines) {
EditToggleView(hwnd);
}
if (bClearUndoHistory) {
UndoRedoRecordingStop();
}
DocChangeTransactionBegin();
SciCall_Cancel();
if (SciCall_GetReadOnly()) {
SciCall_SetReadOnly(false);
}
EditClearAllBookMarks(hwnd);
EditClearAllOccurrenceMarkers(hwnd);
SciCall_SetScrollWidth(1);
SciCall_SetXOffset(0);
EndDocChangeTransaction();
FileVars_Apply(&Globals.fvCurFile);
IgnoreNotifyDocChangedEvent(EVM_None);
EditSetDocumentBuffer(lpstrText, lenText);
ObserveNotifyDocChangedEvent();
Sci_GotoPosChooseCaret(0);
if (bClearUndoHistory) {
UndoRedoRecordingStart();
}
s_bFreezeAppTitle = false;
}
//=============================================================================
//
// EditReInterpretText()
// memory ownership transfered to caller
//
static LPCH EditReInterpretText(LPCCH pchSource, const int szSrc, cpi_enc_t fromCP, cpi_enc_t asCP, int *plen_out) {
int cmbch = 0;
LPCH pchConvText = NULL;
int cwch = MultiByteToWideChar(Encoding_GetCodePage(fromCP), 0, pchSource, szSrc, NULL, 0);
WCHAR* const pwchText = (WCHAR*)AllocMem(((size_t)cwch + 1) * sizeof(WCHAR), HEAP_ZERO_MEMORY);
if (pwchText) {
cwch = MultiByteToWideChar(Encoding_GetCodePage(fromCP), 0, pchSource, szSrc, pwchText, cwch);
cmbch = WideCharToMultiByte(Encoding_GetCodePage(asCP), 0, pwchText, cwch, NULL, 0, NULL, NULL);
pchConvText = (LPCH)AllocMem((size_t)cmbch + 1, HEAP_ZERO_MEMORY);
if (pchConvText) {
cmbch = WideCharToMultiByte(Encoding_GetCodePage(asCP), 0, pwchText, cwch, pchConvText, cmbch, NULL, NULL);
} else {
cmbch = 0;
}
FreeMem(pwchText);
}
if (plen_out) {
*plen_out = cmbch;
}
return pchConvText;
}
//=============================================================================
//
// EditConvertText()
// MultiBytes(Sci) -> WideChar(destination) -> Sci(MultiByte)
//
bool EditConvertText(HWND hwnd, cpi_enc_t encSource, cpi_enc_t encDest)
{
if ((encSource == encDest) || (Encoding_SciCP == encDest)) {
return false;
}
if (!(Encoding_IsValid(encSource) && Encoding_IsValid(encDest))) {
return false;
}
DocPos const length = SciCall_GetTextLength();
if (length <= 0) {
EditSetNewText(hwnd, "", 0, true);
Encoding_Current(encDest);
return true;
}
// moves the gap within Scintilla so that the text of the document is stored consecutively and
// ensure there is a NUL character after the text
const char* const pDoc = SciCall_GetCharacterPointer();
// get text as wide char
ptrdiff_t cbwText = MultiByteToWideCharEx(Encoding_SciCP, 0, pDoc, -1, NULL, 0);
WCHAR* pwchText = AllocMem(cbwText * sizeof(WCHAR), HEAP_ZERO_MEMORY);
if (pwchText) {
MultiByteToWideCharEx(Encoding_SciCP, 0, pDoc, -1, pwchText, cbwText);
// convert wide char to destination multibyte
UINT const cpDst = Encoding_GetCodePage(encDest);
ptrdiff_t cbText = WideCharToMultiByteEx(cpDst, 0, pwchText, -1, NULL, 0, NULL, NULL);
char* pchText = AllocMem(cbText * sizeof(char), HEAP_ZERO_MEMORY);
if (pchText) {
WideCharToMultiByteEx(cpDst, 0, pwchText, -1, pchText, cbText, NULL, NULL);
// re-code to wide char
cbwText = MultiByteToWideCharEx(cpDst, 0, pchText, -1, NULL, 0);
pwchText = ReAllocGrowMem(pwchText, cbwText * sizeof(WCHAR), HEAP_ZERO_MEMORY);
if (pwchText) {
MultiByteToWideCharEx(cpDst, 0, pchText, -1, pwchText, cbwText);
// convert to Scintilla format
cbText = WideCharToMultiByteEx(Encoding_SciCP, 0, pwchText, -1, NULL, 0, NULL, NULL);
pchText = ReAllocGrowMem(pchText, cbText * sizeof(char), HEAP_ZERO_MEMORY);
if (pchText) {
WideCharToMultiByteEx(Encoding_SciCP, 0, pwchText, -1, pchText, cbText, NULL, NULL);
FreeMem(pwchText);
EditSetNewText(hwnd, pchText, (cbText - 1), true);
Encoding_Current(encDest);
FreeMem(pchText);
return true;
}
else {
FreeMem(pwchText);
}
}
else {
FreeMem(pchText);
}
}
else {
FreeMem(pwchText);
}
}
return false;
}
//=============================================================================
//
// EditSetNewEncoding()
//
bool EditSetNewEncoding(HWND hwnd, cpi_enc_t iNewEncoding, bool bSupressWarning)
{
cpi_enc_t iCurrentEncoding = Encoding_GetCurrent();
if (iCurrentEncoding != iNewEncoding) {
// suppress recoding message for certain encodings
UINT const currentCP = Encoding_GetCodePage(iCurrentEncoding);
UINT const targetCP = Encoding_GetCodePage(iNewEncoding);
if (((currentCP == 936) && ((targetCP == 52936) || (targetCP == 54936))) || (((currentCP == 52936) || (currentCP == 54936)) && (targetCP == 936))) {
bSupressWarning = true;
}
if (Sci_IsDocEmpty()) {
bool const doNewEncoding = (Sci_HaveUndoRedoHistory() && !bSupressWarning) ?
IsYesOkayRetryContinue(InfoBoxLng(MB_YESNO, L"MsgConv2", IDS_MUI_ASK_ENCODING2)) : true;
if (doNewEncoding) {
return EditConvertText(hwnd, iCurrentEncoding, iNewEncoding);
}
} else {
if (!bSupressWarning) {
bool const bIsCurANSI = Encoding_IsANSI(iCurrentEncoding);
bool const bIsTargetUTF = Encoding_IsUTF8(iNewEncoding) || Encoding_IsUNICODE(iNewEncoding);
bSupressWarning = bIsCurANSI && bIsTargetUTF;
}
bool const doNewEncoding = (!bSupressWarning) ? IsYesOkayRetryContinue(InfoBoxLng(MB_YESNO, L"MsgConv1", IDS_MUI_ASK_ENCODING)) : true;
if (doNewEncoding) {
return EditConvertText(hwnd, iCurrentEncoding, iNewEncoding);
}
}
}
return false;
}
//=============================================================================
//
// EditIsRecodingNeeded()
//
bool EditIsRecodingNeeded(WCHAR* pszText, int cchLen)
{
if ((pszText == NULL) || (cchLen < 1)) {
return false;
}
UINT codepage = Encoding_GetCodePage(Encoding_GetCurrent());
if ((codepage == CP_UTF7) || (codepage == CP_UTF8)) {
return false;
}
DWORD dwFlags = Encoding_GetWCMBFlagsByCodePage(codepage);
if (dwFlags != 0) {
dwFlags |= (WC_COMPOSITECHECK | WC_DEFAULTCHAR);
}
bool useNullParams = Encoding_IsMBCS(Encoding_GetCurrent()) ? true : false;
BOOL bDefaultCharsUsed = FALSE;
ptrdiff_t cch = 0;
if (useNullParams) {
cch = WideCharToMultiByteEx(codepage, 0, pszText, cchLen, NULL, 0, NULL, NULL);
} else {
cch = WideCharToMultiByteEx(codepage, dwFlags, pszText, cchLen, NULL, 0, NULL, &bDefaultCharsUsed);
}
if (useNullParams && (cch == 0)) {
if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
cch = cchLen; // don't care
}
}
bool bSuccess = ((cch >= cchLen) && (cch != 0xFFFD)) ? true : false;
return (!bSuccess || bDefaultCharsUsed);
}
//=============================================================================
//
// EditGetSelectedText()
//
size_t EditGetSelectedText(LPWSTR pwchBuffer, size_t wchCount)
{
if (!pwchBuffer || (wchCount == 0)) {
return FALSE;
}
size_t const selLen = SciCall_GetSelText(NULL);
if (0 < selLen) {
char* const pszText = AllocMem((selLen + 1), HEAP_ZERO_MEMORY);
if (pszText) {
SciCall_GetSelText(pszText);
size_t const count = (size_t)MultiByteToWideChar(Encoding_SciCP, 0, pszText, -1, pwchBuffer, (int)wchCount);
FreeMem(pszText);
return count;
}
}
if (wchCount > 0) {
pwchBuffer[0] = L'\0';
return 1;
}
return 0;
}
//=============================================================================
//
// EditGetClipboardText()
//
char* EditGetClipboardText(HWND hwnd, bool bCheckEncoding, int* pLineCount, int* pLenLastLn)
{
if (!IsClipboardFormatAvailable(CF_UNICODETEXT) || !OpenClipboard(GetParent(hwnd))) {
char* const pEmpty = AllocMem(1, HEAP_ZERO_MEMORY);
return pEmpty;
}
// get clipboard
HANDLE hmem = GetClipboardData(CF_UNICODETEXT);
WCHAR* pwch = GlobalLock(hmem);
int const wlen = (int)StringCchLenW(pwch,0);
if (bCheckEncoding && EditIsRecodingNeeded(pwch,wlen)) {
const DocPos iPos = SciCall_GetCurrentPos();
const DocPos iAnchor = SciCall_GetAnchor();
// switch encoding to universal UTF-8 codepage
SendWMCommand(Globals.hwndMain, IDM_ENCODING_UTF8);
// restore and adjust selection
if (iPos > iAnchor) {
SciCall_SetSel(iAnchor, iPos);
} else {
SciCall_SetSel(iPos, iAnchor);
}
EditFixPositions(hwnd);
}
// translate to SCI editor component codepage (default: UTF-8)
char* pmch = NULL;
ptrdiff_t mlen = 0;
if (wlen > 0) {
mlen = WideCharToMultiByteEx(Encoding_SciCP, 0, pwch, wlen, NULL, 0, NULL, NULL);
pmch = (char*)AllocMem(mlen + 1, HEAP_ZERO_MEMORY);
if (pmch && mlen != 0) {
ptrdiff_t const cnt = WideCharToMultiByteEx(Encoding_SciCP, 0, pwch, wlen, pmch, SizeOfMem(pmch), NULL, NULL);
if (cnt == 0) {
return pmch;
}
} else {
return pmch;
}
} else {
pmch = AllocMem(1, HEAP_ZERO_MEMORY);
return pmch;
}
int lineCount = 0;
int lenLastLine = 0;
if (SciCall_GetPasteConvertEndings()) {
char* ptmp = (char*)AllocMem((mlen+1)*2, HEAP_ZERO_MEMORY);
if (ptmp) {
char *s = pmch;
char *d = ptmp;
int eolmode = SciCall_GetEOLMode();
for (ptrdiff_t i = 0; (i <= mlen) && (*s != '\0'); ++i, ++lenLastLine) {
if (*s == '\n' || *s == '\r') {
if (eolmode == SC_EOL_CR) {
*d++ = '\r';
} else if (eolmode == SC_EOL_LF) {
*d++ = '\n';
} else { // eolmode == SC_EOL_CRLF
*d++ = '\r';
*d++ = '\n';
}
if ((*s == '\r') && (i + 1 < mlen) && (*(s + 1) == '\n')) {
i++;
s++;
}
s++;
++lineCount;
lenLastLine = 0;
} else {
*d++ = *s++;
}
}
*d = '\0';
int mlen2 = (int)(d - ptmp);
FreeMem(pmch);
pmch = AllocMem((size_t)mlen2 + 1LL, HEAP_ZERO_MEMORY);
if (pmch) {
StringCchCopyA(pmch, SizeOfMem(pmch), ptmp);
FreeMem(ptmp);
ptmp = NULL;
}
}
} else {
// count lines only
char *s = pmch;
for (ptrdiff_t i = 0; (i <= mlen) && (*s != '\0'); ++i, ++lenLastLine) {
if (*s == '\n' || *s == '\r') {
if ((*s == '\r') && (i + 1 < mlen) && (*(s + 1) == '\n')) {
i++;
s++;
}
s++;
++lineCount;
lenLastLine = 0;
}
}
}
GlobalUnlock(hmem);
CloseClipboard();
if (pLineCount) {
*pLineCount = lineCount;
}
if (pLenLastLn) {
*pLenLastLn = lenLastLine;
}
return pmch;
}
//=============================================================================
//
// EditGetClipboardW()
//
void EditGetClipboardW(LPWSTR pwchBuffer, size_t wchLength)
{
if (!IsClipboardFormatAvailable(CF_UNICODETEXT) || !OpenClipboard(Globals.hwndMain)) {
return;
}
HANDLE const hmem = GetClipboardData(CF_UNICODETEXT);
if (hmem) {
const WCHAR* const pwch = GlobalLock(hmem);
if (pwch) {
StringCchCopyW(pwchBuffer, wchLength, pwch);
}
GlobalUnlock(hmem);
}
CloseClipboard();
}
//=============================================================================
//
// EditSetClipboardText()
//
bool EditSetClipboardText(HWND hwnd, const char* pszText, size_t cchText)
{
if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) {
SciCall_CopyText((DocPos)cchText, pszText);
return true;
}
WCHAR* pszTextW = NULL;
ptrdiff_t const cchTextW = MultiByteToWideCharEx(Encoding_SciCP, 0, pszText, cchText, NULL, 0);
if (cchTextW > 1) {
pszTextW = AllocMem((cchTextW + 1) * sizeof(WCHAR), HEAP_ZERO_MEMORY);
if (pszTextW) {
MultiByteToWideCharEx(Encoding_SciCP, 0, pszText, cchText, pszTextW, cchTextW + 1);
pszTextW[cchTextW] = L'\0';
}
}
if (pszTextW) {
SetClipboardText(GetParent(hwnd), pszTextW, cchTextW);
FreeMem(pszTextW);
pszTextW = NULL;
return true;
}
return false;
}
//=============================================================================
//
// EditClearClipboard()
//
bool EditClearClipboard(HWND hwnd)
{
bool ok = false;
if (OpenClipboard(GetParent(hwnd))) {
ok = EmptyClipboard();
CloseClipboard();
}
return ok;
}
//=============================================================================
//
// EditSwapClipboard()
//
bool EditSwapClipboard(HWND hwnd, bool bSkipUnicodeCheck)
{
int lineCount = 0;
int lenLastLine = 0;
char* const pClip = EditGetClipboardText(hwnd, !bSkipUnicodeCheck, &lineCount, &lenLastLine);
if (!pClip) {
return false; // recoding canceled
}
DocPos const clipLen = (DocPos)StringCchLenA(pClip,0);
DocPos const iCurPos = SciCall_GetCurrentPos();
DocPos const iAnchorPos = SciCall_GetAnchor();
UndoTransActionBegin();
char* pszText = NULL;
size_t const len = SciCall_GetSelText(NULL);
if (len > 0) {
pszText = AllocMem((len + 1), HEAP_ZERO_MEMORY);
SciCall_GetSelText(pszText);
SciCall_Paste(); //~SciCall_ReplaceSel(pClip);
EditSetClipboardText(hwnd, pszText, len);
} else {
SciCall_Paste(); //~SciCall_ReplaceSel(pClip);
SciCall_Clear();
}
FreeMem(pszText);
pszText = NULL;
EndUndoTransAction();
if (!Sci_IsMultiOrRectangleSelection()) {
//~UndoTransActionBegin();
if (iCurPos < iAnchorPos) {
EditSetSelectionEx(iCurPos + clipLen, iCurPos, -1, -1);
} else {
EditSetSelectionEx(iAnchorPos, iAnchorPos + clipLen, -1, -1);
}
//~EndUndoTransAction();
} else {
// TODO: restore rectangular selection in case of swap clipboard
}
FreeMem(pClip);
return true;
}
//=============================================================================
//
// EditCopyRangeAppend()
//
bool EditCopyRangeAppend(HWND hwnd, DocPos posBegin, DocPos posEnd, bool bAppend)
{
if (posBegin > posEnd) {
swapos(&posBegin, &posEnd);
}
DocPos const length = (posEnd - posBegin);
if (length == 0) {
return true;
}
const char* const pszText = SciCall_GetRangePointer(posBegin, length);
WCHAR* pszTextW = NULL;
ptrdiff_t cchTextW = 0;
if (pszText && *pszText) {
cchTextW = MultiByteToWideChar(Encoding_SciCP, 0, pszText, (int)length, NULL, 0);
if (cchTextW > 0) {
pszTextW = AllocMem((cchTextW + 1) * sizeof(WCHAR), HEAP_ZERO_MEMORY);
if (pszTextW) {
MultiByteToWideChar(Encoding_SciCP, 0, pszText, (int)length, pszTextW, (int)(cchTextW + 1));
pszTextW[cchTextW] = L'\0';
}
}
}
bool res = false;
HWND const hwndParent = GetParent(hwnd);
if (!bAppend) {
res = SetClipboardText(hwndParent, pszTextW, cchTextW);
FreeMem(pszTextW);
pszTextW = NULL;
return res;
}
// --- Append to Clipboard ---
if (!OpenClipboard(hwndParent)) {
FreeMem(pszTextW);
pszTextW = NULL;
return res;
}
HANDLE const hOld = GetClipboardData(CF_UNICODETEXT);
const WCHAR* pszOld = GlobalLock(hOld);
WCHAR pszSep[3] = { L'\0' };
Sci_GetCurrentEOL_W(pszSep);
size_t cchNewText = cchTextW;
if (pszOld && *pszOld) {
cchNewText += StringCchLen(pszOld, 0) + StringCchLen(pszSep, 0);
}
// Copy Clip & add line break
WCHAR* const pszNewTextW = AllocMem((cchNewText + 1) * sizeof(WCHAR), HEAP_ZERO_MEMORY);
if (pszOld && *pszOld && pszNewTextW) {
StringCchCopy(pszNewTextW, cchNewText + 1, pszOld);
StringCchCat(pszNewTextW, cchNewText + 1, pszSep);
}
GlobalUnlock(hOld);
CloseClipboard();
// Add New
if (pszTextW && *pszTextW && pszNewTextW) {
StringCchCat(pszNewTextW, cchNewText + 1, pszTextW);
res = SetClipboardText(hwndParent, pszNewTextW, cchNewText);
}
FreeMem(pszTextW);
pszTextW = NULL;
FreeMem(pszNewTextW);
return res;
}
//=============================================================================
//
// EditDetectEOLMode() - moved here to handle Unicode files correctly
// by zufuliu (https://github.com/zufuliu/notepad2)
//
void EditDetectEOLMode(LPCSTR lpData, size_t cbData, EditFileIOStatus* const status)
{
if (!lpData || (cbData == 0)) {
return;
}
/* '\r' and '\n' is not reused (e.g. as trailing byte in DBCS) by any known encoding,
it's safe to check whole data byte by byte.*/
DocLn lineCountCRLF = 0;
DocLn lineCountCR = 0;
DocLn lineCountLF = 0;
// tools/GenerateTable.py
static const uint8_t eol_table[16] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, // 00 - 0F
};