-
Notifications
You must be signed in to change notification settings - Fork 172
/
Edit.c
7678 lines (6654 loc) · 220 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
/******************************************************************************
*
*
* Notepad2
*
* Edit.c
* Text File Editing Helper Stuff
*
* See Readme.txt for more information about this source code.
* Please send me your comments to this work.
*
* See License.txt for details about distribution and modification.
*
* (c) Florian Balmer 1996-2011
* florian.balmer@gmail.com
* http://www.flos-freeware.ch
*
*
******************************************************************************/
#include <windows.h>
#include <windowsx.h>
#include <shlwapi.h>
#include <commctrl.h>
#include <commdlg.h>
#if 0
#include <uxtheme.h>
#include <vssym32.h>
#endif
#include <time.h>
#include <stdio.h>
#include <limits.h>
#include <inttypes.h>
#include "SciCall.h"
#include "VectorISA.h"
#include "Helpers.h"
#include "Notepad2.h"
#include "Edit.h"
#include "Styles.h"
#include "Dialogs.h"
#include "resource.h"
extern HWND hwndMain;
extern DWORD dwLastIOError;
extern HWND hDlgFindReplace;
extern UINT cpLastFind;
extern BOOL bReplaceInitialized;
extern int xFindReplaceDlg;
extern int yFindReplaceDlg;
extern int cxFindReplaceDlg;
extern int iDefaultEncoding;
extern int iDefaultEOLMode;
extern BOOL bFixLineEndings;
extern BOOL bAutoStripBlanks;
// Default Codepage and Character Set
extern int iDefaultCodePage;
//extern int iDefaultCharSet;
extern BOOL bLoadANSIasUTF8;
extern BOOL bLoadASCIIasUTF8;
extern BOOL bLoadNFOasOEM;
extern int iSrcEncoding;
extern int iWeakSrcEncoding;
extern int g_DOSEncoding;
extern LPMRULIST mruFind;
extern LPMRULIST mruReplace;
extern WCHAR szCurFile[MAX_PATH + 40];
static DStringW wchPrefixSelection;
static DStringW wchAppendSelection;
static DStringW wchPrefixLines;
static DStringW wchAppendLines;
// see TransliterateText()
#if defined(_MSC_VER) && (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
#define NP2_DYNAMIC_LOAD_ELSCORE_DLL 1
#else
#define NP2_DYNAMIC_LOAD_ELSCORE_DLL 1
#endif
#if NP2_DYNAMIC_LOAD_ELSCORE_DLL
#if _WIN32_WINNT < _WIN32_WINNT_WIN8
extern DWORD kSystemLibraryLoadFlags;
#else
#define kSystemLibraryLoadFlags LOAD_LIBRARY_SEARCH_SYSTEM32
#endif
static HMODULE hELSCoreDLL = NULL;
#else
#pragma comment(lib, "elscore.lib")
#endif
#define MAX_NON_UTF8_SIZE (UINT_MAX/2 - 16)
static struct EditMarkAllStatus {
int findFlag;
Sci_Position iSelCount;
LPSTR pszText;
} editMarkAllStatus;
void Edit_ReleaseResources(void) {
DStringW_Free(&wchPrefixSelection);
DStringW_Free(&wchAppendSelection);
DStringW_Free(&wchPrefixLines);
DStringW_Free(&wchAppendLines);
if (editMarkAllStatus.pszText) {
NP2HeapFree(editMarkAllStatus.pszText);
}
#if NP2_DYNAMIC_LOAD_ELSCORE_DLL
if (hELSCoreDLL != NULL) {
FreeLibrary(hELSCoreDLL);
}
#endif
}
static inline void NotifyRectangleSelection(void) {
MsgBox(MBWARN, IDS_SELRECT);
//ShowNotificationMessage(SC_NOTIFICATIONPOSITION_CENTER, IDS_SELRECT);
}
//=============================================================================
//
// EditSetNewText()
//
extern BOOL bFreezeAppTitle;
extern BOOL bLockedForEditing;
#if defined(_WIN64)
extern BOOL bLargeFileMode;
#endif
extern FILEVARS fvCurFile;
void EditSetNewText(LPCSTR lpstrText, DWORD cbText, Sci_Line lineCount) {
bFreezeAppTitle = TRUE;
bLockedForEditing = FALSE;
SciCall_SetReadOnly(FALSE);
SciCall_Cancel();
SciCall_SetUndoCollection(FALSE);
SciCall_EmptyUndoBuffer();
SciCall_ClearAll();
SciCall_ClearMarker();
SciCall_SetXOffset(0);
FileVars_Apply(&fvCurFile);
#if defined(_WIN64)
// enable conversion between line endings
if (bLargeFileMode || cbText + lineCount >= MAX_NON_UTF8_SIZE) {
int options = SciCall_GetDocumentOptions();
if (!(options & SC_DOCUMENTOPTION_TEXT_LARGE)) {
options |= SC_DOCUMENTOPTION_TEXT_LARGE;
HANDLE pdoc = SciCall_CreateDocument(cbText + 1, options);
EditReplaceDocument(pdoc);
bLargeFileMode = TRUE;
}
}
#endif
if (cbText > 0) {
SciCall_SetModEventMask(SC_MOD_NONE);
#if 0
StopWatch watch;
StopWatch_Start(watch);
#endif
SciCall_SetInitLineCount(lineCount);
SciCall_AddText(cbText, lpstrText);
#if 0
StopWatch_Stop(watch);
StopWatch_ShowLog(&watch, "AddText time");
#endif
SciCall_SetModEventMask(SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
}
SciCall_SetUndoCollection(TRUE);
SciCall_EmptyUndoBuffer();
SciCall_SetSavePoint();
SciCall_GotoPos(0);
SciCall_ChooseCaretX();
bFreezeAppTitle = FALSE;
}
//=============================================================================
//
// EditConvertText()
//
BOOL EditConvertText(UINT cpSource, UINT cpDest, BOOL bSetSavePoint) {
if (cpSource == cpDest) {
return TRUE;
}
const Sci_Position length = SciCall_GetLength();
if (length >= (int)MAX_NON_UTF8_SIZE) {
return TRUE;
}
char *pchText = NULL;
int cbText = 0;
if (length > 0) {
// DBCS: length -> WCHAR: sizeof(WCHAR) * (length / 2) -> UTF-8: kMaxMultiByteCount * (length / 2)
pchText = (char *)NP2HeapAlloc((length + 1) * sizeof(WCHAR));
SciCall_GetText(NP2HeapSize(pchText), pchText);
WCHAR *pwchText = (WCHAR *)NP2HeapAlloc((length + 1) * sizeof(WCHAR));
const int cbwText = MultiByteToWideChar(cpSource, 0, pchText, (int)length, pwchText, (int)(NP2HeapSize(pwchText) / sizeof(WCHAR)));
cbText = WideCharToMultiByte(cpDest, 0, pwchText, cbwText, pchText, (int)(NP2HeapSize(pchText)), NULL, NULL);
NP2HeapFree(pwchText);
}
bLockedForEditing = FALSE;
SciCall_SetReadOnly(FALSE);
SciCall_Cancel();
SciCall_SetUndoCollection(FALSE);
SciCall_EmptyUndoBuffer();
SciCall_ClearAll();
SciCall_ClearMarker();
SciCall_SetCodePage(cpDest);
if (cbText > 0) {
SciCall_AddText(cbText, pchText);
}
if (pchText != NULL) {
NP2HeapFree(pchText);
}
SciCall_EmptyUndoBuffer();
SciCall_SetUndoCollection(TRUE);
SciCall_GotoPos(0);
SciCall_ChooseCaretX();
if (length == 0 && bSetSavePoint) {
SciCall_SetSavePoint();
}
return TRUE;
}
#if defined(_WIN64)
void EditConvertToLargeMode(void) {
int options = SciCall_GetDocumentOptions();
if (options & SC_DOCUMENTOPTION_TEXT_LARGE) {
return;
}
options |= SC_DOCUMENTOPTION_TEXT_LARGE;
const Sci_Position length = SciCall_GetLength();
HANDLE pdoc = SciCall_CreateDocument(length + 1, options);
char *pchText = NULL;
if (length > 0) {
pchText = (char *)NP2HeapAlloc(length + 1);
SciCall_GetText(NP2HeapSize(pchText), pchText);
}
bLockedForEditing = FALSE;
SciCall_SetReadOnly(FALSE);
SciCall_Cancel();
SciCall_SetUndoCollection(FALSE);
SciCall_EmptyUndoBuffer();
SciCall_ClearAll();
SciCall_ClearMarker();
EditReplaceDocument(pdoc);
if (length > 0) {
SciCall_SetModEventMask(SC_MOD_NONE);
SciCall_AddText(length, pchText);
SciCall_SetModEventMask(SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
}
if (pchText != NULL) {
NP2HeapFree(pchText);
}
SciCall_SetUndoCollection(TRUE);
SciCall_EmptyUndoBuffer();
SciCall_GotoPos(0);
SciCall_ChooseCaretX();
SciCall_SetSavePoint();
Style_SetLexer(pLexCurrent, TRUE);
bLargeFileMode = TRUE;
}
#endif
//=============================================================================
//
// EditGetClipboardText()
//
char* EditGetClipboardText(HWND hwnd) {
if (!IsClipboardFormatAvailable(CF_UNICODETEXT) || !OpenClipboard(GetParent(hwnd))) {
return NULL;
}
HANDLE hmem = GetClipboardData(CF_UNICODETEXT);
LPCWSTR pwch = (LPCWSTR)GlobalLock(hmem);
const int wlen = lstrlen(pwch);
const UINT cpEdit = SciCall_GetCodePage();
const int mlen = WideCharToMultiByte(cpEdit, 0, pwch, wlen + 1, NULL, 0, NULL, NULL) - 1;
char *pmch = (char *)LocalAlloc(LPTR, mlen + 1);
char *ptmp = (char *)NP2HeapAlloc(mlen * 4 + 1);
if (pmch && ptmp) {
const char *s = pmch;
char *d = ptmp;
WideCharToMultiByte(cpEdit, 0, pwch, wlen + 1, pmch, mlen + 1, NULL, NULL);
const int iEOLMode = SciCall_GetEOLMode();
for (int i = 0; (i < mlen) && (*s != 0); i++) {
if (*s == '\n' || *s == '\r') {
if (iEOLMode == SC_EOL_CR) {
*d++ = '\r';
} else if (iEOLMode == SC_EOL_LF) {
*d++ = '\n';
} else { // iEOLMode == SC_EOL_CRLF
*d++ = '\r';
*d++ = '\n';
}
if ((*s == '\r') && (i + 1 < mlen) && (*(s + 1) == '\n')) {
i++;
s++;
}
s++;
} else {
*d++ = *s++;
}
}
*d++ = 0;
LocalFree(pmch);
pmch = (char *)LocalAlloc(LPTR, (d - ptmp));
strcpy(pmch, ptmp);
NP2HeapFree(ptmp);
}
GlobalUnlock(hmem);
CloseClipboard();
return pmch;
}
LPWSTR EditGetClipboardTextW(void) {
if (!IsClipboardFormatAvailable(CF_UNICODETEXT) || !OpenClipboard(hwndMain)) {
return NULL;
}
HANDLE hmem = GetClipboardData(CF_UNICODETEXT);
LPCWSTR pwch = (LPCWSTR)GlobalLock(hmem);
const int wlen = lstrlen(pwch);
LPWSTR ptmp = (LPWSTR)NP2HeapAlloc((2*wlen + 1)*sizeof(WCHAR));
if (pwch && ptmp) {
LPCWSTR s = pwch;
LPWSTR d = ptmp;
const int iEOLMode = SciCall_GetEOLMode();
for (int i = 0; (i < wlen) && (*s != 0); i++) {
if (*s == '\n' || *s == '\r') {
if (iEOLMode == SC_EOL_CR) {
*d++ = '\r';
} else if (iEOLMode == SC_EOL_LF) {
*d++ = '\n';
} else { // iEOLMode == SC_EOL_CRLF
*d++ = '\r';
*d++ = '\n';
}
if ((*s == '\r') && (i + 1 < wlen) && (*(s + 1) == '\n')) {
i++;
s++;
}
s++;
} else {
*d++ = *s++;
}
}
*d++ = 0;
}
GlobalUnlock(hmem);
CloseClipboard();
return ptmp;
}
//=============================================================================
//
// EditCopyAppend()
//
BOOL EditCopyAppend(HWND hwnd) {
if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) {
SciCall_Copy(FALSE);
return TRUE;
}
char *pszText;
if (!SciCall_IsSelectionEmpty()) {
if (SciCall_IsRectangleSelection()) {
NotifyRectangleSelection();
return FALSE;
}
const Sci_Position iSelCount = SciCall_GetSelTextLength();
pszText = (char *)NP2HeapAlloc(iSelCount);
SciCall_GetSelText(pszText);
} else {
const Sci_Position cchText = SciCall_GetLength();
pszText = (char *)NP2HeapAlloc(cchText + 1);
SciCall_GetText(NP2HeapSize(pszText), pszText);
}
const UINT cpEdit = SciCall_GetCodePage();
const int cchTextW = MultiByteToWideChar(cpEdit, 0, pszText, -1, NULL, 0);
WCHAR *pszTextW = NULL;
if (cchTextW > 0) {
const WCHAR *pszSep = L"\r\n\r\n";
pszTextW = (WCHAR *)NP2HeapAlloc(sizeof(WCHAR) * (CSTRLEN(L"\r\n\r\n") + cchTextW + 1));
lstrcpy(pszTextW, pszSep);
MultiByteToWideChar(cpEdit, 0, pszText, -1, StrEnd(pszTextW), (int)(NP2HeapSize(pszTextW) / sizeof(WCHAR)));
}
NP2HeapFree(pszText);
BOOL succ = FALSE;
if (OpenClipboard(GetParent(hwnd))) {
HANDLE hOld = GetClipboardData(CF_UNICODETEXT);
LPCWSTR pszOld = (LPCWSTR)GlobalLock(hOld);
HANDLE hNew = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT,
sizeof(WCHAR) * (lstrlen(pszOld) + lstrlen(pszTextW) + 1));
WCHAR *pszNew = (WCHAR *)GlobalLock(hNew);
lstrcpy(pszNew, pszOld);
lstrcat(pszNew, pszTextW);
GlobalUnlock(hOld);
GlobalUnlock(hNew);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, hNew);
CloseClipboard();
succ = TRUE;
}
if (pszTextW != NULL) {
NP2HeapFree(pszTextW);
}
return succ;
}
//=============================================================================
//
// EditDetectEOLMode()
//
void EditDetectEOLMode(LPCSTR lpData, DWORD cbData, EditFileIOStatus *status) {
if (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.*/
Sci_Line lineCountCRLF = 0;
Sci_Line lineCountCR = 0;
Sci_Line lineCountLF = 0;
#if 0
StopWatch watch;
StopWatch_Start(watch);
#endif
// tools/GenerateTable.py
static const uint8_t eolTable[16] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, // 00 - 0F
};
const uint8_t *ptr = (const uint8_t *)lpData;
// No NULL-terminated requirement for *ptr == '\n'
const uint8_t * const end = ptr + cbData - 1;
#if NP2_USE_AVX2
const uint32_t LAST_CR_MASK = (1U << (sizeof(__m256i) - 1));
const __m256i vectCR = _mm256_set1_epi8('\r');
const __m256i vectLF = _mm256_set1_epi8('\n');
while (ptr + sizeof(__m256i) <= end) {
// unaligned loading: line starts at random position.
const __m256i chunk = _mm256_loadu_si256((__m256i *)ptr);
uint32_t maskCR = _mm256_movemask_epi8(_mm256_cmpeq_epi8(chunk, vectCR));
uint32_t maskLF = _mm256_movemask_epi8(_mm256_cmpeq_epi8(chunk, vectLF));
ptr += sizeof(__m256i);
if (maskCR) {
if (maskCR & LAST_CR_MASK) {
maskCR &= LAST_CR_MASK - 1;
if (*ptr == '\n') {
// CR+LF across boundary
++ptr;
++lineCountCRLF;
} else {
// clear highest bit (last CR) to avoid using following code:
// maskCR = (maskCR_LF ^ maskLF) | (maskCR & LAST_CR_MASK);
++lineCountCR;
}
}
// maskCR and maskLF never have some bit set. after shifting maskCR by 1 bit,
// the bits both set in maskCR and maskLF represents CR+LF;
// the bits only set in maskCR or maskLF represents individual CR or LF.
const uint32_t maskCRLF = (maskCR << 1) & maskLF; // CR+LF
const uint32_t maskCR_LF = (maskCR << 1) ^ maskLF;// CR alone or LF alone
maskLF = maskCR_LF & maskLF; // LF alone
maskCR = maskCR_LF ^ maskLF; // CR alone (with one position offset)
if (maskCRLF) {
lineCountCRLF += np2_popcount(maskCRLF);
}
if (maskCR) {
lineCountCR += np2_popcount(maskCR);
}
}
if (maskLF) {
lineCountLF += np2_popcount(maskLF);
}
}
// end NP2_USE_AVX2
#elif NP2_USE_SSE2
const uint32_t LAST_CR_MASK = (1U << (2*sizeof(__m128i) - 1));
const __m128i vectCR = _mm_set1_epi8('\r');
const __m128i vectLF = _mm_set1_epi8('\n');
while (ptr + 2*sizeof(__m128i) <= end) {
// unaligned loading: line starts at random position.
__m128i chunk = _mm_loadu_si128((__m128i *)ptr);
uint32_t maskCR = _mm_movemask_epi8(_mm_cmpeq_epi8(chunk, vectCR));
uint32_t maskLF = _mm_movemask_epi8(_mm_cmpeq_epi8(chunk, vectLF));
chunk = _mm_loadu_si128((__m128i *)(ptr + sizeof(__m128i)));
maskCR |= ((uint32_t)_mm_movemask_epi8(_mm_cmpeq_epi8(chunk, vectCR))) << sizeof(__m128i);
maskLF |= ((uint32_t)_mm_movemask_epi8(_mm_cmpeq_epi8(chunk, vectLF))) << sizeof(__m128i);
ptr += 2*sizeof(__m128i);
if (maskCR) {
if (maskCR & LAST_CR_MASK) {
maskCR &= LAST_CR_MASK - 1;
if (*ptr == '\n') {
// CR+LF across boundary
++ptr;
++lineCountCRLF;
} else {
// clear highest bit (last CR) to avoid using following code:
// maskCR = (maskCR_LF ^ maskLF) | (maskCR & LAST_CR_MASK);
++lineCountCR;
}
}
// maskCR and maskLF never have some bit set. after shifting maskCR by 1 bit,
// the bits both set in maskCR and maskLF represents CR+LF;
// the bits only set in maskCR or maskLF represents individual CR or LF.
const uint32_t maskCRLF = (maskCR << 1) & maskLF; // CR+LF
const uint32_t maskCR_LF = (maskCR << 1) ^ maskLF;// CR alone or LF alone
maskLF = maskCR_LF & maskLF; // LF alone
maskCR = maskCR_LF ^ maskLF; // CR alone (with one position offset)
if (maskCRLF) {
lineCountCRLF += np2_popcount(maskCRLF);
}
if (maskCR) {
lineCountCR += np2_popcount(maskCR);
}
}
if (maskLF) {
lineCountLF += np2_popcount(maskLF);
}
}
// end NP2_USE_SSE2
#endif
do {
// skip to line end
uint8_t ch;
uint8_t type = 0;
while (ptr < end && ((ch = *ptr++) > '\r' || (type = eolTable[ch]) == 0)) {
// nop
}
switch (type) {
case 1: //'\n'
++lineCountLF;
break;
case 2: //'\r'
if (*ptr == '\n') {
++ptr;
++lineCountCRLF;
} else {
++lineCountCR;
}
break;
}
} while (ptr < end);
if (ptr == end) {
switch (*ptr) {
case '\n':
++lineCountLF;
break;
case '\r':
++lineCountCR;
break;
}
}
const Sci_Line linesMax = max_pos(max_pos(lineCountCRLF, lineCountCR), lineCountLF);
// values must kept in same order as SC_EOL_CRLF, SC_EOL_CR, SC_EOL_LF
const Sci_Line linesCount[3] = { lineCountCRLF, lineCountCR, lineCountLF };
int iEOLMode = status->iEOLMode;
if (linesMax != linesCount[iEOLMode]) {
if (linesMax == lineCountCRLF) {
iEOLMode = SC_EOL_CRLF;
} else if (linesMax == lineCountLF) {
iEOLMode = SC_EOL_LF;
} else {
iEOLMode = SC_EOL_CR;
}
}
#if 0
StopWatch_Stop(watch);
StopWatch_ShowLog(&watch, "EOL time");
#if defined(_WIN64)
printf("%s CR+LF:%" PRId64 ", LF: %" PRId64 ", CR: %" PRId64 "\n", __func__, lineCountCRLF, lineCountLF, lineCountCR);
#else
printf("%s CR+LF:%d, LF: %d, CR: %d\n", __func__, lineCountCRLF, lineCountLF, lineCountCR);
#endif
#endif
status->iEOLMode = iEOLMode;
status->bInconsistent = ((!!lineCountCRLF) + (!!lineCountCR) + (!!lineCountLF)) > 1;
status->totalLineCount = lineCountCRLF + lineCountCR + lineCountLF + 1;
status->linesCount[0] = lineCountCRLF;
status->linesCount[1] = lineCountLF;
status->linesCount[2] = lineCountCR;
}
//=============================================================================
//
// EditLoadFile()
//
BOOL EditLoadFile(LPWSTR pszFile, BOOL bSkipEncodingDetection, EditFileIOStatus *status) {
HANDLE hFile = CreateFile(pszFile,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
dwLastIOError = GetLastError();
if (hFile == INVALID_HANDLE_VALUE) {
iSrcEncoding = -1;
iWeakSrcEncoding = -1;
return FALSE;
}
LARGE_INTEGER fileSize;
fileSize.QuadPart = 0;
if (!GetFileSizeEx(hFile, &fileSize)) {
dwLastIOError = GetLastError();
CloseHandle(hFile);
iSrcEncoding = -1;
iWeakSrcEncoding = -1;
return FALSE;
}
// display real path name
if (IsVistaAndAbove()) {
WCHAR path[MAX_PATH] = L"";
// since Windows Vista
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
if (GetFinalPathNameByHandleW(hFile, path, MAX_PATH, FILE_NAME_OPENED))
#else
typedef DWORD (WINAPI *GetFinalPathNameByHandleSig)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
GetFinalPathNameByHandleSig pfnGetFinalPathNameByHandle = (GetFinalPathNameByHandleSig)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetFinalPathNameByHandleW");
if (pfnGetFinalPathNameByHandle && pfnGetFinalPathNameByHandle(hFile, path, MAX_PATH, FILE_NAME_OPENED))
#endif
{
if (StrNEqual(path, L"\\\\?\\", CSTRLEN(L"\\\\?\\"))) {
WCHAR *p = path + 4;
if (StrNEqual(p, L"UNC\\", CSTRLEN(L"UNC\\"))) {
p += 2;
*p = L'\\';
}
lstrcpy(pszFile, p);
}
}
}
// Check if a warning message should be displayed for large files
#if defined(_WIN64)
// less than 1/3 available physical memory:
// 1. The buffers we allocated below or when saving file, depends on encoding.
// 2. Scintilla's content buffer and style buffer, see CellBuffer class. The style buffer can be disabled by using SCLEX_NULL and SC_DOCUMENTOPTION_STYLES_NONE.
// 3. Extra memory when moving gaps on editing, it may requires more than 2/3 physical memory.
// large file TODO: https://github.com/zufuliu/notepad2/issues/125
// [ ] [> 4 GiB] use SetFilePointerEx() and ReadFile()/WriteFile() to read/write file.
// [-] [> 2 GiB] fix encoding conversion with MultiByteToWideChar() and WideCharToMultiByte().
LONGLONG maxFileSize = INT64_C(0x100000000);
#else
// 2 GiB: ptrdiff_t / Sci_Position used in Scintilla
LONGLONG maxFileSize = INT64_C(0x80000000);
#endif
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
if (GlobalMemoryStatusEx(&statex)) {
ULONGLONG maxMem = statex.ullTotalPhys/3U;
if (maxMem < (ULONGLONG)maxFileSize) {
maxFileSize = (LONGLONG)maxMem;
}
} else {
dwLastIOError = GetLastError();
}
if (fileSize.QuadPart > maxFileSize) {
CloseHandle(hFile);
status->bFileTooBig = TRUE;
iSrcEncoding = -1;
iWeakSrcEncoding = -1;
WCHAR tchDocSize[32];
WCHAR tchMaxSize[32];
WCHAR tchDocBytes[32];
WCHAR tchMaxBytes[32];
StrFormatByteSize(fileSize.QuadPart, tchDocSize, COUNTOF(tchDocSize));
StrFormatByteSize(maxFileSize, tchMaxSize, COUNTOF(tchMaxSize));
_i64tow(fileSize.QuadPart, tchDocBytes, 10);
_i64tow(maxFileSize, tchMaxBytes, 10);
FormatNumberStr(tchDocBytes);
FormatNumberStr(tchMaxBytes);
MsgBox(MBWARN, IDS_WARNLOADBIGFILE, pszFile, tchDocSize, tchDocBytes, tchMaxSize, tchMaxBytes);
return FALSE;
}
char *lpData = (char *)NP2HeapAlloc((SIZE_T)(fileSize.QuadPart) + 16);
DWORD cbData = 0;
// prevent unsigned integer overflow.
const DWORD readLen = max_u((DWORD)(NP2HeapSize(lpData) - 2), (DWORD)fileSize.QuadPart);
const BOOL bReadSuccess = ReadFile(hFile, lpData, readLen, &cbData, NULL);
dwLastIOError = GetLastError();
CloseHandle(hFile);
if (!bReadSuccess) {
NP2HeapFree(lpData);
iSrcEncoding = -1;
iWeakSrcEncoding = -1;
return FALSE;
}
BOOL bPreferOEM = FALSE;
if (bLoadNFOasOEM) {
LPCWSTR const pszExt = pszFile + lstrlen(pszFile) - 4;
if (pszExt >= pszFile && (StrCaseEqual(pszExt, L".nfo") || StrCaseEqual(pszExt, L".diz"))) {
bPreferOEM = TRUE;
}
}
if (!Encoding_IsValid(iDefaultEncoding)) {
iDefaultEncoding = CPI_UTF8;
}
int _iDefaultEncoding = bPreferOEM ? g_DOSEncoding : iDefaultEncoding;
if (iWeakSrcEncoding != -1 && Encoding_IsValid(iWeakSrcEncoding)) {
_iDefaultEncoding = iWeakSrcEncoding;
}
int iEncoding = CPI_DEFAULT;
const BOOL utf8Sig = cbData? IsUTF8Signature(lpData) : FALSE;
BOOL bBOM = FALSE;
BOOL bReverse = FALSE;
status->iEOLMode = iLineEndings[iDefaultEOLMode];
status->bInconsistent = FALSE;
status->totalLineCount = 1;
if (cbData == 0) {
FileVars_Init(NULL, 0, &fvCurFile);
if (iSrcEncoding == -1) {
if (bLoadANSIasUTF8 && !bPreferOEM) {
iEncoding = CPI_UTF8;
} else {
iEncoding = _iDefaultEncoding;
}
} else {
iEncoding = iSrcEncoding;
}
SciCall_SetCodePage((mEncoding[iEncoding].uFlags & NCP_DEFAULT) ? iDefaultCodePage : SC_CP_UTF8);
EditSetEmptyText();
SciCall_SetEOLMode(status->iEOLMode);
} else if (cbData < MAX_NON_UTF8_SIZE && ((iSrcEncoding == CPI_UNICODE || iSrcEncoding == CPI_UNICODEBE) // reload as UTF-16
|| (!bSkipEncodingDetection && iSrcEncoding == -1 && !utf8Sig && IsUnicode(lpData, cbData, &bBOM, &bReverse))
)) {
if (iSrcEncoding == CPI_UNICODE) {
bBOM = (lpData[0] == '\xFF' && lpData[1] == '\xFE');
bReverse = FALSE;
} else if (iSrcEncoding == CPI_UNICODEBE) {
bBOM = (lpData[0] == '\xFE' && lpData[1] == '\xFF');
}
if (iSrcEncoding == CPI_UNICODEBE || bReverse) {
_swab(lpData, lpData, cbData);
if (bBOM) {
iEncoding = CPI_UNICODEBEBOM;
} else {
iEncoding = CPI_UNICODEBE;
}
} else {
if (bBOM) {
iEncoding = CPI_UNICODEBOM;
} else {
iEncoding = CPI_UNICODE;
}
}
// cbData/2 => WCHAR, WCHAR*3 => UTF-8
char *lpDataUTF8 = (char *)NP2HeapAlloc((cbData + 1)*sizeof(WCHAR));
cbData = WideCharToMultiByte(CP_UTF8, 0, (bBOM ? (LPWSTR)lpData + 1 : (LPWSTR)lpData),
(int)(bBOM ? (cbData / sizeof(WCHAR)) : (cbData / sizeof(WCHAR)) + 1),
lpDataUTF8, (int)NP2HeapSize(lpDataUTF8), NULL, NULL);
if (cbData == 0) {
cbData = WideCharToMultiByte(CP_ACP, 0, (bBOM ? (LPWSTR)lpData + 1 : (LPWSTR)lpData),
-1, lpDataUTF8, (int)NP2HeapSize(lpDataUTF8), NULL, NULL);
status->bUnicodeErr = TRUE;
}
EditDetectEOLMode(lpDataUTF8, cbData - 1, status);
FileVars_Init(lpDataUTF8, cbData - 1, &fvCurFile);
SciCall_SetCodePage(SC_CP_UTF8);
EditSetNewText(lpDataUTF8, cbData - 1, status->totalLineCount);
NP2HeapFree(lpDataUTF8);
} else {
FileVars_Init(lpData, cbData, &fvCurFile);
if (iSrcEncoding == -1) {
iSrcEncoding = FileVars_GetEncoding(&fvCurFile);
}
if ((iSrcEncoding == CPI_UTF8 || iSrcEncoding == CPI_UTF8SIGN) // reload as UTF-8 or UTF-8 filevar
|| ((iSrcEncoding == -1) && ((bLoadANSIasUTF8 && !bPreferOEM) // load ANSI as UTF-8
|| ((!bSkipEncodingDetection || cbData >= MAX_NON_UTF8_SIZE) && (utf8Sig || IsUTF8(lpData, cbData)))
))
) {
SciCall_SetCodePage(SC_CP_UTF8);
if (utf8Sig) {
EditDetectEOLMode(lpData + 3, cbData - 3, status);
EditSetNewText(lpData + 3, cbData - 3, status->totalLineCount);
iEncoding = CPI_UTF8SIGN;
} else {
EditDetectEOLMode(lpData, cbData, status);
EditSetNewText(lpData, cbData, status->totalLineCount);
iEncoding = CPI_UTF8;
}
} else {
iEncoding = iSrcEncoding;
if (iEncoding == -1) {
if (fvCurFile.mask & FV_ENCODING) {
iEncoding = CPI_DEFAULT;
} else {
if ((iWeakSrcEncoding != -1) && (mEncoding[iWeakSrcEncoding].uFlags & NCP_INTERNAL)) {
iEncoding = iDefaultEncoding;
} else {
iEncoding = _iDefaultEncoding;
}
}
}
const UINT uCodePage = mEncoding[iEncoding].uCodePage;
if (cbData < MAX_NON_UTF8_SIZE && ((mEncoding[iEncoding].uFlags & NCP_8BIT)
|| ((mEncoding[iEncoding].uFlags & NCP_7BIT) && IsUTF7(lpData, cbData))
)) {
LPWSTR lpDataWide = (LPWSTR)NP2HeapAlloc(cbData * sizeof(WCHAR) + 16);
const int cbDataWide = MultiByteToWideChar(uCodePage, 0, lpData, cbData, lpDataWide, (int)(NP2HeapSize(lpDataWide) / sizeof(WCHAR)));
NP2HeapFree(lpData);
lpData = (char *)NP2HeapAlloc(cbDataWide * kMaxMultiByteCount + 16);
cbData = WideCharToMultiByte(CP_UTF8, 0, lpDataWide, cbDataWide, lpData, (int)NP2HeapSize(lpData), NULL, NULL);
NP2HeapFree(lpDataWide);
EditDetectEOLMode(lpData, cbData, status);
SciCall_SetCodePage(SC_CP_UTF8);
EditSetNewText(lpData, cbData, status->totalLineCount);
} else {
EditDetectEOLMode(lpData, cbData, status);
SciCall_SetCodePage(iDefaultCodePage);
EditSetNewText(lpData, cbData, status->totalLineCount);
iEncoding = CPI_DEFAULT;
}
}
}
NP2HeapFree(lpData);
status->iEncoding = iEncoding;
iSrcEncoding = -1;
iWeakSrcEncoding = -1;
return TRUE;
}
//=============================================================================
//
// EditSaveFile()
//
BOOL EditSaveFile(HWND hwnd, LPCWSTR pszFile, BOOL bSaveCopy, EditFileIOStatus *status) {
HANDLE hFile = CreateFile(pszFile,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
dwLastIOError = GetLastError();
// failure could be due to missing attributes (2k/XP)
if (hFile == INVALID_HANDLE_VALUE) {
DWORD dwAttributes = GetFileAttributes(pszFile);
if (dwAttributes != INVALID_FILE_ATTRIBUTES) {
dwAttributes = dwAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
hFile = CreateFile(pszFile,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL | dwAttributes,
NULL);
dwLastIOError = GetLastError();
}
}
if (hFile == INVALID_HANDLE_VALUE) {
return FALSE;
}
// ensure consistent line endings
if (bFixLineEndings) {
EditEnsureConsistentLineEndings();
}
// strip trailing blanks
if (bAutoStripBlanks) {
EditStripTrailingBlanks(hwnd, TRUE);
}
BOOL bWriteSuccess;
// get text
DWORD cbData = (DWORD)SciCall_GetLength();
char *lpData = NULL;
if (cbData == 0) {
bWriteSuccess = SetEndOfFile(hFile);
dwLastIOError = GetLastError();
} else {
DWORD dwBytesWritten;
int iEncoding = status->iEncoding;
UINT uFlags = mEncoding[iEncoding].uFlags;
if (cbData >= MAX_NON_UTF8_SIZE) {
// save as UTF-8 or ANSI
if (!(uFlags & (NCP_DEFAULT | NCP_UTF8))) {
if (uFlags & NCP_UNICODE_BOM) {
iEncoding = CPI_UTF8SIGN;
} else {
iEncoding = CPI_UTF8;
}
uFlags = mEncoding[iEncoding].uFlags;
}
}
lpData = (char *)NP2HeapAlloc(cbData + 1);
SciCall_GetText(NP2HeapSize(lpData), lpData);
// FIXME: move checks in front of disk file access
/*if ((uFlags & NCP_UNICODE) == 0 && (uFlags & NCP_UTF8_SIGN) == 0) {
BOOL bEncodingMismatch = TRUE;
FILEVARS fv;
FileVars_Init(lpData, cbData, &fv);
if (fv.mask & FV_ENCODING) {
int iAltEncoding;
if (FileVars_IsValidEncoding(&fv)) {
iAltEncoding = FileVars_GetEncoding(&fv);
if (iAltEncoding == iEncoding)
bEncodingMismatch = FALSE;
else if ((mEncoding[iAltEncoding].uFlags & NCP_UTF8) && (uFlags & NCP_UTF8))
bEncodingMismatch = FALSE;
}
if (bEncodingMismatch) {
Encoding_GetLabel(iAltEncoding);
Encoding_GetLabel(iEncoding);
InfoBox(0, L"MsgEncodingMismatch", IDS_ENCODINGMISMATCH,
mEncoding[iAltEncoding].wchLabel,
mEncoding[iEncoding].wchLabel);
}
}
}*/
if (uFlags & NCP_UNICODE) {
SetEndOfFile(hFile);
LPWSTR lpDataWide = (LPWSTR)NP2HeapAlloc(cbData * sizeof(WCHAR) + 16);
const int cbDataWide = MultiByteToWideChar(CP_UTF8, 0, lpData, cbData, lpDataWide, (int)(NP2HeapSize(lpDataWide) / sizeof(WCHAR)));
if (uFlags & NCP_UNICODE_BOM) {
if (uFlags & NCP_UNICODE_REVERSE) {
WriteFile(hFile, (LPCVOID)"\xFE\xFF", 2, &dwBytesWritten, NULL);
} else {