-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1746 lines (1478 loc) · 59.9 KB
/
script.js
File metadata and controls
1746 lines (1478 loc) · 59.9 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
const editor = document.getElementById('editor');
const highlighting = document.getElementById('highlighting-content');
const highlightingPre = document.getElementById('highlighting');
const lineNumbers = document.getElementById('line-numbers');
const tabbar = document.getElementById('tabbar');
// Status bar elements
const sbType = document.getElementById('sb-type');
const sbLength = document.getElementById('sb-length');
const sbPosition = document.getElementById('sb-position');
const sbEol = document.getElementById('sb-eol');
const sbEncoding = document.getElementById('sb-encoding');
// State Management
let tabs = [];
let activeTabId = null;
let fileCounter = 0;
let currentZoom = 14;
// --- UNIVERSAL DIALOG ENGINE ---
let msgBoxCallback = null;
function closeMsgBox(result = null) {
document.getElementById('msg-box-modal').style.display = 'none';
if (msgBoxCallback) msgBoxCallback(result);
}
window.customAlert = function(msg) {
return new Promise(resolve => {
document.getElementById('msg-box-title').textContent = 'Notepad++ Web Clone';
document.getElementById('msg-box-text').textContent = msg;
document.getElementById('msg-box-input-container').style.display = 'none';
document.getElementById('msg-box-actions').innerHTML = `<button onclick="closeMsgBox(true)" style="padding: 4px 20px;">OK</button>`;
document.getElementById('msg-box-modal').style.display = 'block';
centerModal(document.getElementById('msg-box-modal'));
msgBoxCallback = resolve;
});
};
window.customConfirm = function(msg) {
return new Promise(resolve => {
document.getElementById('msg-box-title').textContent = 'Confirm';
document.getElementById('msg-box-text').textContent = msg;
document.getElementById('msg-box-input-container').style.display = 'none';
document.getElementById('msg-box-actions').innerHTML = `
<button onclick="closeMsgBox(true)" style="padding: 4px 20px;">OK</button>
<button onclick="closeMsgBox(false)" style="padding: 4px 20px;">Cancel</button>
`;
document.getElementById('msg-box-modal').style.display = 'block';
centerModal(document.getElementById('msg-box-modal'));
msgBoxCallback = resolve;
});
};
window.customPrompt = function(msg, defaultText = '') {
return new Promise(resolve => {
document.getElementById('msg-box-title').textContent = 'Input';
document.getElementById('msg-box-text').textContent = msg;
document.getElementById('msg-box-input-container').style.display = 'block';
let input = document.getElementById('msg-box-input');
input.value = defaultText;
document.getElementById('msg-box-actions').innerHTML = `
<button onclick="closeMsgBox(document.getElementById('msg-box-input').value)" style="padding: 4px 20px;">OK</button>
<button onclick="closeMsgBox(null)" style="padding: 4px 20px;">Cancel</button>
`;
document.getElementById('msg-box-modal').style.display = 'block';
centerModal(document.getElementById('msg-box-modal'));
input.focus();
input.select();
input.onkeydown = function(e) {
if(e.key === 'Enter') {
e.preventDefault();
closeMsgBox(input.value);
}
};
msgBoxCallback = resolve;
});
};
// SYSTEM FEATURE EXPLANATION ENGINE
function requireDesktop(featureName) {
let msg = "";
switch (featureName) {
case 'Windows Explorer':
case 'Command Prompt':
msg = `Opening native OS shell processes like ${featureName} is blocked by browser security sandboxes to prevent malicious execution.`;
break;
case 'Folder as Workspace':
case 'Find in Files':
msg = `The "${featureName}" feature requires recursively scanning and indexing local system directories, which web browsers restrict for privacy and security.`;
break;
case 'Begin/End Select':
case 'Column Mode':
case 'Column Editor':
msg = `Advanced vertical column manipulation ("${featureName}") relies on native text rendering APIs that are not supported by standard web textareas.`;
break;
case 'Function Auto-Completion':
msg = `Intelligent "${featureName}" requires parsing syntax trees across multiple files using background threading, which isn't implemented in this lightweight web version.`;
break;
case 'Clipboard HTML Parsing':
case 'OS Clipboard History':
msg = `Browsers limit access to the OS clipboard history and rich MIME-types to protect user privacy. Only basic text clipboard operations are permitted in the web clone.`;
break;
case 'OS File Execution':
case 'Open in New Instance':
msg = `Spawning new native application processes or executing local files is strictly prohibited within a browser sandbox environment.`;
break;
case 'Character Panel':
msg = `Rendering the native OS-level "${featureName}" requires desktop UI toolkits outside the scope of standard DOM elements.`;
break;
case 'Reverse Search Engine':
case 'Hex Range Search':
msg = `Deep binary hex-level searching and complex reverse buffering requires raw memory access handled by the native desktop engine.`;
break;
case 'Bracket Matching Selection':
case 'Lexer Token Styling':
msg = `Deep lexical token modification and recursive matching for "${featureName}" relies on the native Scintilla C++ engine used by the desktop app.`;
break;
case 'Gutter Marking':
case 'Gutter Bookmarks':
case 'Change History':
case 'Hide Lines':
msg = `Injecting interactive visual markers, persistent bookmarks, or hiding specific line indices requires the native Scintilla rendering engine, rather than standard HTML wrapping.`;
break;
case 'Always on Top':
case 'Window Manager':
case 'Split Screen Views':
case 'Close Multiple Tabs Panel':
msg = `Manipulating window stacking order ("${featureName}") or spawning split-view frames is controlled by your desktop window manager, not the browser.`;
break;
case 'Render CR/LF Symbols':
msg = `Rendering invisible carriage return and line feed bytes as physical visual glyphs is a custom drawing feature not supported by standard browser text rendering.`;
break;
case 'Code Folding':
msg = `Collapsing and folding code blocks hierarchically requires a dedicated background lexical parser, which isn't present in this DOM-based clone.`;
break;
case 'Project Panels':
case 'Document Map':
case 'Document List':
case 'Function List':
msg = `Generating secondary UI panels for "${featureName}" (like minimaps or function trees) requires background file parsing and threading built into the native desktop app.`;
break;
case 'RTF Export Plugin':
case 'Plugins Admin':
msg = `Notepad++ plugins are compiled C++ DLL files. A web browser sandbox cannot load or execute native desktop binaries.`;
break;
case 'Network Proxy Settings':
msg = `Browser-based applications inherently use the network proxy settings of the browser itself. You cannot set a custom proxy just for this specific tab.`;
break;
case 'Style Configurator':
case 'Theme Import':
case 'Dark Mode Engine':
msg = `Modifying raw UI themes and injecting dynamic CSS overrides requires writing to the native OS user-profile configuration files.`;
break;
case 'Context Menu Customization':
msg = `Modifying the application right-click context menus requires native desktop UI injection and configuration file parsing.`;
break;
case 'User Defined Languages':
msg = `Building a custom lexical parser for a new language requires writing and compiling native XML rules into the C++ Scintilla engine.`;
break;
default:
msg = `The "${featureName}" feature requires deep integration with the operating system which is not possible in a web browser sandbox.`;
}
customAlert(msg + `\n\nPlease download the official Notepad++ desktop application for Windows to use this feature.`);
}
function setTextDirection(dir) {
const container = document.getElementById('editor-container');
const editor = document.getElementById('editor');
if (dir === 'rtl') {
container.classList.add('is-rtl');
document.body.classList.add('is-rtl-measurer');
editor.setAttribute('dir', 'rtl');
} else {
container.classList.remove('is-rtl');
document.body.classList.remove('is-rtl-measurer');
editor.setAttribute('dir', 'ltr');
}
updateLineNumbers(editor.value);
syncScroll();
}
// --- Language to Extension Mapping Dictionary ---
function getExtensionForLang(lang) {
const extMap = {
'none': 'txt', 'actionscript': 'as', 'ada': 'ada', 'asn1': 'asn', 'aspnet': 'asp', 'nasm': 'asm', 'autoit': 'au3',
'bash': 'sh', 'batch': 'bat', 'basic': 'bb',
'c': 'c', 'cpp': 'cpp', 'csharp': 'cs', 'cmake': 'cmake', 'cobol': 'cbl', 'coffeescript': 'coffee', 'css': 'css',
'd': 'd', 'dart': 'dart', 'diff': 'diff', 'docker': 'dockerfile',
'elixir': 'ex', 'elm': 'elm', 'erlang': 'erl',
'fsharp': 'fs', 'fortran': 'f90',
'go': 'go', 'graphql': 'graphql', 'groovy': 'groovy',
'haskell': 'hs', 'hollywood': 'hws', 'html': 'html',
'ini': 'ini', 'icon': 'icn',
'java': 'java', 'javascript': 'js', 'json': 'json', 'jsx': 'jsx', 'julia': 'jl',
'kotlin': 'kt',
'latex': 'tex', 'less': 'less', 'lisp': 'lisp', 'lua': 'lua',
'makefile': 'mak', 'markdown': 'md', 'matlab': 'mat',
'nim': 'nim', 'nix': 'nix',
'objectivec': 'm', 'ocaml': 'ml',
'pascal': 'pas', 'perl': 'pl', 'php': 'php', 'powershell': 'ps1', 'python': 'py',
'r': 'r', 'ruby': 'rb', 'rust': 'rs',
'sass': 'sass', 'scala': 'scala', 'scheme': 'scm', 'sql': 'sql', 'swift': 'swift',
'tcl': 'tcl', 'tsx': 'tsx', 'typescript': 'ts',
'visual-basic': 'vb', 'xml': 'xml', 'yaml': 'yaml'
};
return extMap[lang] || 'txt';
}
// --- Core Editor Logic ---
function handleInput() {
const text = editor.value;
const currentTab = getActiveTab();
currentTab.content = text;
let prismText = text;
if (prismText.endsWith('\n')) {
prismText += ' ';
}
highlighting.textContent = prismText;
if (typeof Prism !== 'undefined') {
Prism.highlightElement(highlighting);
}
updateLineNumbers(text);
updateStatusBarLength();
updateStatusBarCursor();
syncScroll();
if (currentTab.isSaved) {
currentTab.isSaved = false;
renderTabs();
}
}
function syncScroll() {
highlightingPre.scrollTop = editor.scrollTop;
highlightingPre.scrollLeft = editor.scrollLeft;
lineNumbers.scrollTop = editor.scrollTop;
// CRITICAL CHROME FIX: If the text area scrolled further than the pre layer's max height, snap it back to match perfectly.
if (editor.scrollTop > highlightingPre.scrollTop) {
editor.scrollTop = highlightingPre.scrollTop;
}
}
// Ensure scroll events are tracked constantly on the mouse wheel, not just when typing
editor.addEventListener('scroll', syncScroll);
// CRITICAL FIX: The Exact-Height Block Mirror Engine
function updateLineNumbers(text) {
const lines = text.split('\n');
const wrapper = document.getElementById('code-wrapper');
const isWrap = wrapper.classList.contains('word-wrap');
// Ensure mathematically perfect line-height calculations from computed CSS
const cs = window.getComputedStyle(editor);
const fontSize = parseFloat(cs.fontSize) || currentZoom;
const lh = fontSize * 1.5;
let numbersHtml = '';
// Fast path for non-word-wrap mode
if (!isWrap) {
for (let i = 1; i <= lines.length; i++) {
numbersHtml += `<div style="height: ${lh}px; line-height: ${lh}px; display: flex; align-items: flex-start; justify-content: flex-end;">${i}</div>`;
}
lineNumbers.innerHTML = numbersHtml;
return;
}
// --- WORD WRAP MEASUREMENT ENGINE ---
let measurer = document.getElementById('wrap-measurer');
if (!measurer) {
measurer = document.createElement('div');
measurer.id = 'wrap-measurer';
document.body.appendChild(measurer);
}
// Exact copy of Textarea computation styles to prevent sub-pixel drift
measurer.style.position = 'fixed';
measurer.style.visibility = 'hidden';
measurer.style.top = '-9999px';
measurer.style.left = '-9999px';
measurer.style.whiteSpace = 'pre-wrap';
measurer.style.wordWrap = 'break-word';
measurer.style.overflowWrap = 'anywhere';
measurer.style.wordBreak = 'break-all';
measurer.style.fontFamily = cs.fontFamily;
measurer.style.fontSize = cs.fontSize;
measurer.style.lineHeight = cs.lineHeight;
measurer.style.boxSizing = cs.boxSizing;
measurer.style.tabSize = cs.tabSize;
measurer.style.letterSpacing = cs.letterSpacing;
measurer.style.wordSpacing = cs.wordSpacing;
// Width must match clientWidth exactly to account for scrollbars
measurer.style.width = editor.clientWidth + 'px';
measurer.style.paddingLeft = cs.paddingLeft;
measurer.style.paddingRight = cs.paddingRight;
measurer.style.paddingTop = '0px';
measurer.style.paddingBottom = '0px';
// Load lines into independent block-level dummy containers
let dummyHtml = '';
for (let i = 0; i < lines.length; i++) {
let safeLine = lines[i].replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
if (safeLine.length === 0) safeLine = ' '; // Empty lines still hold native height
dummyHtml += `<div style="display:block; width:100%;">${safeLine}</div>`;
}
measurer.innerHTML = dummyHtml;
// Measure the browser naturally assigned to each wrapped line
const children = measurer.children;
for (let i = 0; i < children.length; i++) {
let h = children[i].offsetHeight;
let linesWrapped = Math.round(h / lh);
if (linesWrapped < 1) linesWrapped = 1;
let snappedHeight = linesWrapped * lh;
numbersHtml += `<div style="height: ${snappedHeight}px; line-height: ${lh}px; display: flex; align-items: flex-start; justify-content: flex-end;">${i + 1}</div>`;
}
lineNumbers.innerHTML = numbersHtml;
}
// Recalculate word wrap heights dynamically if the user resizes the window
window.addEventListener('resize', () => {
const wrapper = document.getElementById('code-wrapper');
if (wrapper.classList.contains('word-wrap')) {
updateLineNumbers(editor.value);
}
});
function zoomEditor(direction) {
if (direction !== 0) {
currentZoom += (direction * 2);
}
if(currentZoom < 8) currentZoom = 8;
if(currentZoom > 48) currentZoom = 48;
document.documentElement.style.setProperty('--editor-font-size', currentZoom + 'px');
document.documentElement.style.setProperty('--editor-line-height', (currentZoom * 1.5) + 'px');
const prefFontSize = document.getElementById('pref-font-size');
if(prefFontSize) prefFontSize.value = currentZoom;
updateLineNumbers(editor.value);
syncScroll();
}
// --- Language / Syntax Management ---
function setLanguage(lang) {
const currentTab = getActiveTab();
if(!currentTab) return;
currentTab.lang = lang;
highlighting.className = `language-${lang}`;
if (typeof Prism !== 'undefined') {
Prism.highlightElement(highlighting);
}
updateMenuCheckmarks('lang-check', lang);
let langDisplay = lang === 'none' ? 'Normal text file' : lang.toUpperCase() + ' source file';
sbType.textContent = langDisplay;
document.title = `${currentTab.title} - Notepad++ Clone`;
}
// --- Encoding Management ---
function setEncoding(enc) {
const currentTab = getActiveTab();
if(!currentTab) return;
currentTab.encoding = enc;
updateMenuCheckmarks('enc-check', enc);
sbEncoding.textContent = enc;
document.title = `${currentTab.title} - Notepad++ Clone`;
}
function convertEncoding(enc) {
setEncoding(enc);
}
function setEOL(eol) {
const currentTab = getActiveTab();
if(!currentTab) return;
currentTab.eol = eol;
sbEol.textContent = eol;
}
function updateMenuCheckmarks(prefix, activeValue) {
const allChecks = document.querySelectorAll(`span[id^="${prefix}"]`);
allChecks.forEach(span => {
span.textContent = '';
});
const activeCheck = document.getElementById(`${prefix}-${activeValue}`);
if(activeCheck) {
activeCheck.textContent = '✓ ';
}
}
// --- Status Bar Logic ---
function updateStatusBarLength() {
const text = editor.value;
const len = text.length;
const lines = text.split('\n').length;
sbLength.textContent = `length : ${len} lines : ${lines}`;
}
function updateStatusBarCursor() {
const text = editor.value;
const pos = editor.selectionStart;
const textBeforeCursor = text.substring(0, pos);
const linesBeforeCursor = textBeforeCursor.split('\n');
const currentLine = linesBeforeCursor.length;
const currentCol = linesBeforeCursor[linesBeforeCursor.length - 1].length + 1;
sbPosition.textContent = `Ln : ${currentLine} Col : ${currentCol} Pos : ${pos}`;
}
// --- Tab Management Logic ---
function newTab(title = null, content = '', lang = 'none', encoding = 'UTF-8') {
fileCounter++;
const newId = `tab-${Date.now()}`;
const tabTitle = title || `new ${fileCounter}`;
tabs.push({
id: newId,
title: tabTitle,
content: content,
isSaved: true,
lang: lang,
encoding: encoding,
eol: 'Windows (CR LF)'
});
switchTab(newId);
}
function switchTab(id) {
const currentTab = getActiveTab();
if (currentTab) {
currentTab.scrollTop = editor.scrollTop;
currentTab.scrollLeft = editor.scrollLeft;
}
activeTabId = id;
const tab = getActiveTab();
editor.value = tab.content;
let prismText = tab.content;
if (prismText.endsWith('\n')) {
prismText += ' ';
}
highlighting.textContent = prismText;
highlighting.className = `language-${tab.lang}`;
if (typeof Prism !== 'undefined') {
Prism.highlightElement(highlighting);
}
updateLineNumbers(tab.content);
updateMenuCheckmarks('enc-check', tab.encoding);
updateMenuCheckmarks('lang-check', tab.lang);
sbEncoding.textContent = tab.encoding;
sbEol.textContent = tab.eol;
let langDisplay = tab.lang === 'none' ? 'Normal text file' : tab.lang.toUpperCase() + ' source file';
sbType.textContent = langDisplay;
updateStatusBarLength();
updateStatusBarCursor();
setTimeout(() => {
editor.scrollTop = tab.scrollTop || 0;
editor.scrollLeft = tab.scrollLeft || 0;
syncScroll();
}, 0);
renderTabs();
}
function closeActiveTab() {
if(activeTabId) closeTab(new Event('dummy'), activeTabId);
}
async function closeTab(event, id) {
event.stopPropagation();
const tabToClose = tabs.find(t => t.id === id);
if (!tabToClose.isSaved) {
if (!(await customConfirm(`Are you sure you want to close tab "${tabToClose.title}"? all unsaved data will be lost.`))) return;
}
tabs = tabs.filter(t => t.id !== id);
if (tabs.length === 0) newTab();
else if (activeTabId === id) switchTab(tabs[tabs.length - 1].id);
else renderTabs();
}
async function closeAllTabs() {
if(await customConfirm("Close all tabs? Unsaved changes will be lost.")) {
tabs = [];
fileCounter = 0;
newTab();
}
}
async function closeAllButThis() {
if(tabs.length <= 1) return;
if(await customConfirm("Close all other tabs? Unsaved changes will be lost.")) {
tabs = tabs.filter(t => t.id === activeTabId);
renderTabs();
}
}
async function closeAllToLeft() {
const idx = tabs.findIndex(t => t.id === activeTabId);
if(idx <= 0) return;
if(await customConfirm("Close all tabs to the left? Unsaved changes will be lost.")) {
tabs = tabs.slice(idx);
renderTabs();
}
}
async function closeAllToRight() {
const idx = tabs.findIndex(t => t.id === activeTabId);
if(idx === -1 || idx === tabs.length - 1) return;
if(await customConfirm("Close all tabs to the right? Unsaved changes will be lost.")) {
tabs = tabs.slice(0, idx + 1);
renderTabs();
}
}
function sortTabsAlphabetically() {
tabs.sort((a, b) => a.title.localeCompare(b.title));
renderTabs();
}
function getActiveTab() {
return tabs.find(t => t.id === activeTabId);
}
function renderTabs() {
tabbar.innerHTML = '';
tabs.forEach(tab => {
const isActive = tab.id === activeTabId ? 'active' : '';
const iconClass = tab.isSaved ? 'saved' : 'unsaved';
const iconSrc = tab.isSaved
? "https://proxy.duckduckgo.com/iu/?u=https://i.imgur.com/YnSqZRe.png"
: "https://proxy.duckduckgo.com/iu/?u=https://i.imgur.com/fE2wgSM.png";
const tabEl = document.createElement('div');
tabEl.className = `tab ${isActive}`;
tabEl.onclick = () => switchTab(tab.id);
// Native Right-Click Rename Hook
tabEl.oncontextmenu = async (e) => {
e.preventDefault();
let newName = await customPrompt("Rename tab:", tab.title);
if(newName !== null && newName.trim() !== "") {
tab.title = newName;
renderTabs();
}
};
// --- Drag and Drop for Tabs ---
tabEl.draggable = true;
tabEl.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', tab.id);
setTimeout(() => tabEl.classList.add('dragging'), 0);
});
tabEl.addEventListener('dragover', (e) => {
e.preventDefault();
tabEl.classList.add('drag-over');
});
tabEl.addEventListener('dragleave', (e) => {
tabEl.classList.remove('drag-over');
});
tabEl.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
tabEl.classList.remove('drag-over');
const draggedId = e.dataTransfer.getData('text/plain');
if (draggedId && draggedId !== tab.id) {
const draggedIndex = tabs.findIndex(t => t.id === draggedId);
const targetIndex = tabs.findIndex(t => t.id === tab.id);
if (draggedIndex !== -1 && targetIndex !== -1) {
const [draggedTab] = tabs.splice(draggedIndex, 1);
tabs.splice(targetIndex, 0, draggedTab);
renderTabs();
}
}
});
tabEl.addEventListener('dragend', (e) => {
tabEl.classList.remove('dragging');
document.querySelectorAll('.tab').forEach(t => t.classList.remove('drag-over'));
});
// ------------------------------
tabEl.innerHTML = `
<img src="${iconSrc}" class="floppy-icon ${iconClass}" alt="save state">
<span class="tab-title">${tab.title}</span>
<span class="tab-close" onclick="closeTab(event, '${tab.id}')"></span>
`;
tabbar.appendChild(tabEl);
});
const activeTab = getActiveTab();
if(activeTab) {
document.title = `${activeTab.isSaved ? '' : '*'}${activeTab.title} - Notepad++ Clone`;
}
}
// --- File Operations ---
function triggerFileOpen() {
document.getElementById('fileInput').click();
}
function handleFileOpen(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
const ext = file.name.split('.').pop().toLowerCase();
let lang = 'none';
if (['html', 'htm'].includes(ext)) lang = 'html';
else if (['js'].includes(ext)) lang = 'javascript';
else if (['css'].includes(ext)) lang = 'css';
else if (['json'].includes(ext)) lang = 'json';
else if (['py'].includes(ext)) lang = 'python';
else if (['php'].includes(ext)) lang = 'php';
else if (['c'].includes(ext)) lang = 'c';
else if (['cpp', 'cc', 'h', 'hpp'].includes(ext)) lang = 'cpp';
else if (['cs'].includes(ext)) lang = 'csharp';
else if (['java'].includes(ext)) lang = 'java';
else if (['xml'].includes(ext)) lang = 'xml';
else if (['yml', 'yaml'].includes(ext)) lang = 'yaml';
else if (['bat', 'cmd'].includes(ext)) lang = 'batch';
else if (['sh', 'bash'].includes(ext)) lang = 'bash';
else if (['hws'].includes(ext)) lang = 'hollywood';
newTab(file.name, content, lang);
};
reader.readAsText(file);
event.target.value = '';
}
function executeDownload(tab, fileName) {
let fileContent = tab.content;
let blobParts = [];
if (tab.encoding === 'UTF-8 BOM') {
blobParts.push(new Uint8Array([0xEF, 0xBB, 0xBF]));
} else if (tab.encoding === 'UTF-16 LE BOM') {
blobParts.push(new Uint8Array([0xFF, 0xFE]));
} else if (tab.encoding === 'UTF-16 BE BOM') {
blobParts.push(new Uint8Array([0xFE, 0xFF]));
}
blobParts.push(fileContent);
const blob = new Blob(blobParts, { type: "text/plain;charset=utf-8" });
const a = document.createElement("a");
const url = URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
tab.isSaved = true;
renderTabs();
}
function saveCurrentFile() {
const tab = getActiveTab();
if(!tab) return;
let fileName = tab.title;
if (!fileName.includes('.')) {
fileName = `${fileName}.${getExtensionForLang(tab.lang)}`;
}
executeDownload(tab, fileName);
}
async function saveCopyAs() {
const tab = getActiveTab();
if(!tab) return;
let defaultExt = getExtensionForLang(tab.lang);
let suggestedName = tab.title;
if (!suggestedName.includes('.')) {
suggestedName = `${suggestedName}.${defaultExt}`;
}
let newFileName = await customPrompt("Save Copy As... \n\nEnter file name with extension:", suggestedName);
if (newFileName === null || newFileName.trim() === "") return;
executeDownload(tab, newFileName);
}
async function renameActiveTab() {
const tab = getActiveTab();
if(!tab) return;
let newName = await customPrompt("Rename tab:", tab.title);
if(newName !== null && newName.trim() !== "") {
tab.title = newName;
renderTabs();
}
}
async function saveAsFile() {
const tab = getActiveTab();
if(!tab) return;
let defaultExt = getExtensionForLang(tab.lang);
let suggestedName = tab.title;
if (!suggestedName.includes('.')) {
suggestedName = `${suggestedName}.${defaultExt}`;
}
let newFileName = await customPrompt("Save As... \n\nEnter file name with extension:", suggestedName);
if (newFileName === null || newFileName.trim() === "") {
return;
}
tab.title = newFileName;
const ext = newFileName.split('.').pop().toLowerCase();
let newLang = tab.lang;
if (['html', 'htm'].includes(ext)) newLang = 'html';
else if (['js'].includes(ext)) newLang = 'javascript';
else if (['css'].includes(ext)) newLang = 'css';
else if (['json'].includes(ext)) newLang = 'json';
else if (['py'].includes(ext)) newLang = 'python';
else if (['php'].includes(ext)) newLang = 'php';
else if (['cpp', 'c', 'h'].includes(ext)) newLang = 'cpp';
else if (['hws'].includes(ext)) newLang = 'hollywood';
if (newLang !== tab.lang) {
setLanguage(newLang);
}
executeDownload(tab, newFileName);
}
function saveAllFiles() {
tabs.forEach(tab => {
if(!tab.isSaved) {
let fileName = tab.title;
if (!fileName.includes('.')) {
fileName = `${fileName}.${getExtensionForLang(tab.lang)}`;
}
let blobParts = [];
if (tab.encoding === 'UTF-8 BOM') blobParts.push(new Uint8Array([0xEF, 0xBB, 0xBF]));
else if (tab.encoding === 'UTF-16 LE BOM') blobParts.push(new Uint8Array([0xFF, 0xFE]));
else if (tab.encoding === 'UTF-16 BE BOM') blobParts.push(new Uint8Array([0xFE, 0xFF]));
blobParts.push(tab.content);
const blob = new Blob(blobParts, { type: "text/plain;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
tab.isSaved = true;
}
});
renderTabs();
}
async function moveToRecycleBin() {
if(await customConfirm("Move current file to Recycle Bin? (Simulated)")) {
closeActiveTab();
}
}
// ==========================================
// SESSION LOAD & SAVE
// ==========================================
function saveSession() {
const sessionData = JSON.stringify({
tabs: tabs,
activeTabId: activeTabId,
fileCounter: fileCounter
}, null, 2);
const blob = new Blob([sessionData], { type: "application/json" });
const a = document.createElement("a");
const url = URL.createObjectURL(blob);
a.href = url;
a.download = "session.json";
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
function triggerSessionLoad() {
document.getElementById('sessionInput').click();
}
function handleSessionLoad(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
if (data && Array.isArray(data.tabs)) {
tabs = data.tabs;
activeTabId = data.activeTabId;
fileCounter = data.fileCounter || tabs.length;
if (tabs.length > 0) {
let tabToSwitch = tabs.find(t => t.id === activeTabId);
if (!tabToSwitch) activeTabId = tabs[0].id;
switchTab(activeTabId);
} else {
newTab();
}
customAlert("Session loaded successfully!");
} else {
customAlert("Invalid session file format.");
}
} catch (err) {
customAlert("Failed to parse session file. Make sure it is a valid .json session.");
}
};
reader.readAsText(file);
event.target.value = '';
}
// ==========================================
// FIND AND REPLACE ENGINE
// ==========================================
// NEW ENGINE: Mathematically forces the editor to scroll directly to the index without relying on browser focus
function scrollToTarget(index) {
const wrapper = document.getElementById('code-wrapper');
const isWrap = wrapper.classList.contains('word-wrap');
const textBefore = editor.value.substring(0, index);
const linesBefore = textBefore.split('\n');
const cs = window.getComputedStyle(editor);
const fontSize = parseFloat(cs.fontSize) || currentZoom;
const lh = fontSize * 1.5;
let targetTop = 0;
if (!isWrap) {
targetTop = (linesBefore.length - 1) * lh;
// Approximate horizontal scroll for standard monospace text
const charWidth = fontSize * 0.602;
const currentLineText = linesBefore[linesBefore.length - 1];
const targetLeft = currentLineText.length * charWidth;
editor.scrollLeft = Math.max(0, targetLeft - (editor.clientWidth / 2) + 50);
} else {
let measurer = document.getElementById('wrap-measurer');
if (!measurer || measurer.children.length === 0) {
updateLineNumbers(editor.value);
measurer = document.getElementById('wrap-measurer');
}
if (measurer && measurer.children.length >= linesBefore.length) {
for (let i = 0; i < linesBefore.length - 1; i++) {
let h = measurer.children[i].offsetHeight;
let linesWrapped = Math.round(h / lh);
if (linesWrapped < 1) linesWrapped = 1;
targetTop += (linesWrapped * lh);
}
} else {
targetTop = (linesBefore.length - 1) * lh;
}
}
// Set scroll position to visually center the target line
editor.scrollTop = Math.max(0, targetTop - (editor.clientHeight / 2) + (lh / 2));
syncScroll();
}
function showFindModal(isReplace) {
const modal = document.getElementById('find-modal');
modal.style.display = 'block';
centerModal(modal);
document.getElementById('find-modal-title').textContent = isReplace ? 'Replace' : 'Find';
document.getElementById('replace-row').style.display = isReplace ? 'flex' : 'none';
document.getElementById('btn-replace').style.display = isReplace ? 'inline-block' : 'none';
document.getElementById('btn-replace-all').style.display = isReplace ? 'inline-block' : 'none';
let selectedText = editor.value.substring(editor.selectionStart, editor.selectionEnd);
if (selectedText && !selectedText.includes('\n')) {
document.getElementById('find-input').value = selectedText;
}
document.getElementById('find-input').focus();
}
function closeFindModal() {
document.getElementById('find-modal').style.display = 'none';
editor.focus();
}
function doFindNext() {
let query = document.getElementById('find-input').value;
if (!query) return;
let matchCase = document.getElementById('find-match-case').checked;
let wrap = document.getElementById('find-wrap').checked;
let text = editor.value;
let pos = editor.selectionEnd;
let targetText = matchCase ? text : text.toLowerCase();
let targetQuery = matchCase ? query : query.toLowerCase();
let index = targetText.indexOf(targetQuery, pos);
if (index === -1 && wrap) {
index = targetText.indexOf(targetQuery, 0);
}
if (index !== -1) {
editor.focus();
editor.setSelectionRange(index, index + query.length);
// FIXED: Replaced standard browser hack with mathematical precision scroll
scrollToTarget(index);
} else {
customAlert(`Cannot find "${query}"`);
}
}
function doReplace() {
let query = document.getElementById('find-input').value;
let replacement = document.getElementById('replace-input').value;
if (!query) return;
let matchCase = document.getElementById('find-match-case').checked;
let selectedText = editor.value.substring(editor.selectionStart, editor.selectionEnd);
let isMatch = matchCase ? (selectedText === query) : (selectedText.toLowerCase() === query.toLowerCase());
if (isMatch) {
let success = false;
try { success = document.execCommand('insertText', false, replacement); } catch(e){}
if(!success) {
editor.setRangeText(replacement, editor.selectionStart, editor.selectionEnd, 'end');
}
handleInput();
}
doFindNext();
}
function doReplaceAll() {
let query = document.getElementById('find-input').value;
let replacement = document.getElementById('replace-input').value;
if (!query) return;
let matchCase = document.getElementById('find-match-case').checked;