-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1360 lines (1125 loc) · 49.1 KB
/
script.js
File metadata and controls
1360 lines (1125 loc) · 49.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Modern Code Editor - Main JavaScript File
class ModernCodeEditor {
constructor() {
this.files = new Map();
this.currentFile = null;
this.currentLanguage = 'python';
this.autoSaveInterval = null;
this.highlightTimeout = null;
this.settings = {
theme: 'dark',
fontSize: '14',
tabSize: '4'
};
this.init();
}
init() {
this.loadSettings();
this.setupEventListeners();
this.createDefaultFiles();
this.setupAutoSave();
this.updateLineNumbers();
this.applySettings();
this.setupAutoComplete(); // Add auto-complete setup
}
setupEventListeners() {
// Editor events
const codeEditor = document.getElementById('codeEditor');
codeEditor.addEventListener('input', () => {
this.updateLineNumbers();
this.updateCurrentFileContent();
// Debounced syntax highlighting for better performance
clearTimeout(this.highlightTimeout);
this.highlightTimeout = setTimeout(() => {
this.applySyntaxHighlighting();
}, 300);
});
codeEditor.addEventListener('keydown', (e) => {
this.handleKeyDown(e);
});
// Button events
document.getElementById('newFileBtn').addEventListener('click', () => {
this.showNewFileModal();
});
document.getElementById('runBtn').addEventListener('click', () => {
this.runCode();
});
document.getElementById('saveBtn').addEventListener('click', () => {
this.saveCurrentFile();
});
document.getElementById('settingsBtn').addEventListener('click', () => {
this.showSettingsModal();
});
document.getElementById('clearOutputBtn').addEventListener('click', () => {
this.clearOutput();
});
// Language selector
document.getElementById('languageSelect').addEventListener('change', (e) => {
this.currentLanguage = e.target.value;
this.updateLanguageSelector();
});
// Modal events
document.getElementById('closeSettingsBtn').addEventListener('click', () => {
this.hideModal('settingsModal');
});
document.getElementById('closeNewFileBtn').addEventListener('click', () => {
this.hideModal('newFileModal');
});
document.getElementById('createFileBtn').addEventListener('click', () => {
this.createNewFile();
});
document.getElementById('cancelNewFileBtn').addEventListener('click', () => {
this.hideModal('newFileModal');
});
// Settings change events
document.getElementById('themeSelect').addEventListener('change', (e) => {
this.settings.theme = e.target.value;
this.applySettings();
this.saveSettings();
});
document.getElementById('fontSizeSelect').addEventListener('change', (e) => {
this.settings.fontSize = e.target.value;
this.applySettings();
this.saveSettings();
});
document.getElementById('tabSizeSelect').addEventListener('change', (e) => {
this.settings.tabSize = e.target.value;
this.applySettings();
this.saveSettings();
});
// Window events
window.addEventListener('beforeunload', () => {
this.saveAllFiles();
});
}
createDefaultFiles() {
// Create sample Python file
const pythonFile = {
name: 'main.py',
language: 'python',
content: `# Welcome to Modern Code Editor!
# This is a sample Python file
def greet(name):
"""A simple greeting function"""
return f"Hello, {name}!"
def calculate_sum(a, b):
"""Calculate the sum of two numbers"""
return a + b
if __name__ == "__main__":
print("Welcome to the Modern Code Editor!")
print(greet("Developer"))
result = calculate_sum(10, 20)
print(f"Sum of 10 and 20 is: {result}")
# Let's try a simple loop
for i in range(5):
print(f"Count: {i}")
`,
lastModified: new Date()
};
// Create sample Java file
const javaFile = {
name: 'Main.java',
language: 'java',
content: `// Welcome to Modern Code Editor!
// This is a sample Java file showcasing enhanced features
import java.util.*;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the Modern Code Editor!");
// Create an instance and call methods
Calculator calc = new Calculator();
int result = calc.add(10, 20);
System.out.println("Sum of 10 and 20 is: " + result);
// Demonstrate modern Java features
List<String> items = Arrays.asList("Java", "Python", "JavaScript");
// Stream API usage
List<String> upperItems = items.stream()
.map(String::toUpperCase)
.filter(s -> s.startsWith("J"))
.collect(Collectors.toList());
// Enhanced for loop
for (String item : upperItems) {
System.out.println("Item: " + item);
}
// Lambda expressions
items.forEach(item -> System.out.println("Processing: " + item));
// Optional usage
Optional<String> firstItem = items.stream().findFirst();
firstItem.ifPresent(item -> System.out.println("First item: " + item));
// Try-with-resources
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
} catch (Exception e) {
System.err.println("Error reading input: " + e.getMessage());
}
}
}
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
// Generic method example
public <T extends Number> T max(T a, T b) {
return a.doubleValue() > b.doubleValue() ? a : b;
}
}
// Record example (Java 14+)
record Point(int x, int y) {
public double distance() {
return Math.sqrt(x * x + y * y);
}
}
// Sealed class example (Java 17+)
sealed abstract class Shape permits Circle, Rectangle {
public abstract double area();
}
final class Circle extends Shape {
private final double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
final class Rectangle extends Shape {
private final double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}`,
lastModified: new Date()
};
this.files.set('main.py', pythonFile);
this.files.set('Main.java', javaFile);
this.updateFileList();
this.openFile('main.py');
}
showNewFileModal() {
document.getElementById('newFileModal').style.display = 'block';
document.getElementById('fileNameInput').value = '';
document.getElementById('fileNameInput').focus();
}
hideModal(modalId) {
document.getElementById(modalId).style.display = 'none';
}
createNewFile() {
const fileName = document.getElementById('fileNameInput').value.trim();
const language = document.getElementById('fileLanguageSelect').value;
if (!fileName) {
alert('Please enter a file name');
return;
}
// Add file extension if not provided
let finalFileName = fileName;
if (!fileName.includes('.')) {
const extensions = {
'python': '.py',
'java': '.java',
'javascript': '.js',
'html': '.html',
'css': '.css'
};
finalFileName = fileName + extensions[language];
}
if (this.files.has(finalFileName)) {
alert('A file with this name already exists');
return;
}
const newFile = {
name: finalFileName,
language: language,
content: this.getTemplateForLanguage(language),
lastModified: new Date()
};
this.files.set(finalFileName, newFile);
this.updateFileList();
this.openFile(finalFileName);
this.hideModal('newFileModal');
}
getTemplateForLanguage(language) {
const templates = {
'python': '# New Python file\n\n',
'java': '// New Java file\n\n',
'javascript': '// New JavaScript file\n\n',
'html': '<!DOCTYPE html>\n<html>\n<head>\n <title>New HTML File</title>\n</head>\n<body>\n \n</body>\n</html>',
'css': '/* New CSS file */\n\n'
};
return templates[language] || '';
}
updateFileList() {
const fileList = document.getElementById('fileList');
fileList.innerHTML = '';
this.files.forEach((file, fileName) => {
const fileItem = document.createElement('div');
fileItem.className = `file-item ${this.currentFile === fileName ? 'active' : ''}`;
fileItem.setAttribute('data-language', file.language);
fileItem.innerHTML = `
<i class="fas fa-file-code"></i>
<span>${fileName}</span>
`;
fileItem.addEventListener('click', () => {
this.openFile(fileName);
});
fileList.appendChild(fileItem);
});
}
openFile(fileName) {
const file = this.files.get(fileName);
if (!file) return;
this.currentFile = fileName;
this.currentLanguage = file.language;
// Update editor content
document.getElementById('codeEditor').value = file.content;
document.getElementById('languageSelect').value = file.language;
// Update file list and tabs
this.updateFileList();
this.updateFileTabs();
this.updateLineNumbers();
this.updateLanguageSelector();
// Apply syntax highlighting with a small delay to ensure content is loaded
setTimeout(() => {
this.applySyntaxHighlighting();
}, 100);
}
updateFileTabs() {
const fileTabs = document.getElementById('fileTabs');
fileTabs.innerHTML = '';
this.files.forEach((file, fileName) => {
const tab = document.createElement('div');
tab.className = `file-tab ${this.currentFile === fileName ? 'active' : ''}`;
tab.setAttribute('data-language', file.language);
tab.innerHTML = `
<span>${fileName}</span>
<button class="close-tab" onclick="editor.closeFile('${fileName}')">×</button>
`;
tab.addEventListener('click', () => {
this.openFile(fileName);
});
fileTabs.appendChild(tab);
});
}
closeFile(fileName) {
if (this.files.size <= 1) {
alert('Cannot close the last file');
return;
}
this.files.delete(fileName);
if (this.currentFile === fileName) {
// Open the first available file
const firstFile = Array.from(this.files.keys())[0];
this.openFile(firstFile);
} else {
this.updateFileList();
this.updateFileTabs();
}
}
updateCurrentFileContent() {
if (this.currentFile) {
const file = this.files.get(this.currentFile);
if (file) {
file.content = document.getElementById('codeEditor').value;
file.lastModified = new Date();
}
}
}
saveCurrentFile() {
if (this.currentFile) {
this.updateCurrentFileContent();
this.saveAllFiles();
this.showOutput(`File "${this.currentFile}" saved successfully!`, 'success');
}
}
saveAllFiles() {
this.updateCurrentFileContent();
localStorage.setItem('modernCodeEditor_files', JSON.stringify(Array.from(this.files.entries())));
}
loadSettings() {
const savedSettings = localStorage.getItem('modernCodeEditor_settings');
if (savedSettings) {
this.settings = { ...this.settings, ...JSON.parse(savedSettings) };
}
}
saveSettings() {
localStorage.setItem('modernCodeEditor_settings', JSON.stringify(this.settings));
}
applySettings() {
// Apply theme
document.body.className = `theme-${this.settings.theme}`;
// Apply font size
document.getElementById('codeEditor').style.fontSize = `${this.settings.fontSize}px`;
document.getElementById('lineNumbers').style.fontSize = `${this.settings.fontSize}px`;
// Apply tab size
document.getElementById('codeEditor').style.tabSize = this.settings.tabSize;
// Update selectors
document.getElementById('themeSelect').value = this.settings.theme;
document.getElementById('fontSizeSelect').value = this.settings.fontSize;
document.getElementById('tabSizeSelect').value = this.settings.tabSize;
}
showSettingsModal() {
document.getElementById('settingsModal').style.display = 'block';
}
updateLineNumbers() {
const codeEditor = document.getElementById('codeEditor');
const lineNumbers = document.getElementById('lineNumbers');
const lines = codeEditor.value.split('\n');
lineNumbers.innerHTML = lines.map((_, index) => index + 1).join('\n');
}
handleKeyDown(e) {
if (e.key === 'Tab') {
e.preventDefault();
const start = e.target.selectionStart;
const end = e.target.selectionEnd;
const tabSize = parseInt(this.settings.tabSize);
const spaces = ' '.repeat(tabSize);
e.target.value = e.target.value.substring(0, start) + spaces + e.target.value.substring(end);
e.target.selectionStart = e.target.selectionEnd = start + tabSize;
this.updateLineNumbers();
this.updateCurrentFileContent();
}
}
updateLanguageSelector() {
const languageSelect = document.getElementById('languageSelect');
const languageSelectorDiv = document.querySelector('.language-selector');
const sidebar = document.querySelector('.sidebar');
const mainEditor = document.querySelector('.main-editor');
languageSelect.value = this.currentLanguage;
// Update the data-language attribute for CSS styling
if (languageSelectorDiv) {
languageSelectorDiv.setAttribute('data-language', this.currentLanguage);
}
// Update the sidebar with the active language
if (sidebar) {
sidebar.setAttribute('data-active-language', this.currentLanguage);
}
// Update the main editor with the active language
if (mainEditor) {
mainEditor.setAttribute('data-active-language', this.currentLanguage);
}
this.applySyntaxHighlighting();
}
applySyntaxHighlighting() {
const codeEditor = document.getElementById('codeEditor');
const content = codeEditor.value;
// Remove existing syntax classes
codeEditor.className = '';
// Add language-specific class
if (this.currentLanguage === 'python' || this.currentLanguage === 'java') {
codeEditor.classList.add(`syntax-${this.currentLanguage}`);
}
// Apply real-time syntax highlighting
this.highlightSyntax(content);
}
highlightSyntax(content) {
if (!this.currentLanguage) return;
// For now, we'll apply basic syntax highlighting through CSS classes
// The actual highlighting will be handled by the CSS selectors
// This approach is more performant and doesn't interfere with text editing
const codeEditor = document.getElementById('codeEditor');
const lineNumbers = document.getElementById('lineNumbers');
// Remove any existing language classes
codeEditor.className = '';
lineNumbers.className = 'line-numbers';
// Add the appropriate language class for CSS-based highlighting
if (this.currentLanguage === 'python' || this.currentLanguage === 'java') {
codeEditor.classList.add(`syntax-${this.currentLanguage}`);
lineNumbers.classList.add(`syntax-${this.currentLanguage}`);
}
// Store the current content for potential future use
this.currentHighlightedContent = content;
}
highlightPython(content) {
// Python syntax highlighting rules
const keywords = [
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield'
];
const builtins = [
'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray',
'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals',
'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance',
'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max',
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',
'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',
'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip'
];
let highlighted = content;
// Highlight keywords
keywords.forEach(keyword => {
const regex = new RegExp(`\\b${keyword}\\b`, 'g');
highlighted = highlighted.replace(regex, `<span class="keyword">${keyword}</span>`);
});
// Highlight builtins
builtins.forEach(builtin => {
const regex = new RegExp(`\\b${builtin}\\b`, 'g');
highlighted = highlighted.replace(regex, `<span class="builtin">${builtin}</span>`);
});
// Highlight strings (single and double quotes)
highlighted = highlighted.replace(/(['"`])((?:(?!\1)[^\\]|\\.)*)\1/g, '<span class="string">$&</span>');
// Highlight f-strings
highlighted = highlighted.replace(/(f['"`])((?:(?!\1)[^\\]|\\.)*)\1/g, '<span class="fstring">$&</span>');
// Highlight comments
highlighted = highlighted.replace(/(#.*$)/gm, '<span class="comment">$1</span>');
// Highlight numbers
highlighted = highlighted.replace(/\b(\d+(?:\.\d+)?)\b/g, '<span class="number">$1</span>');
// Highlight function definitions
highlighted = highlighted.replace(/\bdef\s+(\w+)\s*\(/g, 'def <span class="function">$1</span>(');
// Highlight class definitions
highlighted = highlighted.replace(/\bclass\s+(\w+)/g, 'class <span class="class">$1</span>');
// Highlight decorators
highlighted = highlighted.replace(/^(\s*@\w+)/gm, '<span class="decorator">$1</span>');
return highlighted;
}
highlightJava(content) {
// Enhanced Java syntax highlighting rules
const keywords = [
'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch',
'char', 'class', 'const', 'continue', 'default', 'do', 'double',
'else', 'enum', 'extends', 'final', 'finally', 'float', 'for',
'goto', 'if', 'implements', 'import', 'instanceof', 'int', 'interface',
'long', 'native', 'new', 'package', 'private', 'protected', 'public',
'return', 'short', 'static', 'strictfp', 'super', 'switch',
'synchronized', 'this', 'throw', 'throws', 'transient', 'try',
'void', 'volatile', 'while', 'record', 'sealed', 'permits', 'non-sealed'
];
const types = [
'String', 'Integer', 'Double', 'Float', 'Long', 'Short', 'Byte',
'Boolean', 'Character', 'Object', 'Array', 'List', 'Set', 'Map',
'ArrayList', 'HashMap', 'HashSet', 'LinkedList', 'Vector', 'Stack',
'Queue', 'PriorityQueue', 'TreeMap', 'TreeSet', 'LinkedHashMap',
'LinkedHashSet', 'WeakHashMap', 'IdentityHashMap', 'EnumMap',
'ConcurrentHashMap', 'CopyOnWriteArrayList', 'CopyOnWriteArraySet',
'Optional', 'Stream', 'Collector', 'Function', 'Predicate', 'Consumer',
'Supplier', 'BiFunction', 'BiPredicate', 'BiConsumer', 'Runnable',
'Callable', 'Future', 'CompletableFuture', 'Executor', 'ExecutorService'
];
const annotations = [
'Override', 'Deprecated', 'SuppressWarnings', 'SafeVarargs',
'FunctionalInterface', 'Native', 'Target', 'Retention', 'Documented',
'Inherited', 'Repeatable', 'SpringBootApplication', 'Component',
'Service', 'Repository', 'Controller', 'Autowired', 'Value',
'Configuration', 'Bean', 'Qualifier', 'Primary', 'Profile'
];
let highlighted = content;
// Highlight keywords
keywords.forEach(keyword => {
const regex = new RegExp(`\\b${keyword}\\b`, 'g');
highlighted = highlighted.replace(regex, `<span class="keyword">${keyword}</span>`);
});
// Highlight types
types.forEach(type => {
const regex = new RegExp(`\\b${type}\\b`, 'g');
highlighted = highlighted.replace(regex, `<span class="type">${type}</span>`);
});
// Highlight annotations
annotations.forEach(annotation => {
const regex = new RegExp(`\\b${annotation}\\b`, 'g`);
highlighted = highlighted.replace(regex, `<span class="annotation">${annotation}</span>`);
});
// Highlight strings
highlighted = highlighted.replace(/"([^"\\]|\\.)*"/g, '<span class="string">$&</span>');
// Highlight single-line comments
highlighted = highlighted.replace(/(\/\/.*$)/gm, '<span class="comment">$1</span>');
// Highlight multi-line comments
highlighted = highlighted.replace(/(\/\*[\s\S]*?\*\/)/g, '<span class="comment">$1</span>');
// Highlight numbers
highlighted = highlighted.replace(/\b(\d+(?:\.\d+)?(?:L|f|d)?)\b/g, '<span class="number">$1</span>');
// Highlight class definitions with generics support
highlighted = highlighted.replace(/\b(public\s+)?(abstract\s+)?(final\s+)?(sealed\s+)?(non-sealed\s+)?class\s+(\w+)(\s*<[^>]*>)?/g,
(match, pub, abs, fin, sealed, nonSealed, className, generics) => {
return `${pub || ''}${abs || ''}${fin || ''}${sealed || ''}${nonSealed || ''}class <span class="class">${className}</span>${generics || ''}`;
});
// Highlight method definitions with generics
highlighted = highlighted.replace(/\b(public|private|protected|static|final|abstract|native|synchronized)\s+(\w+(?:<[^>]*>)?)\s+(\w+)\s*\(/g,
(match, modifier, returnType, methodName) => {
return `<span class="modifier">${modifier}</span> <span class="type">${returnType}</span> <span class="function">${methodName}</span>(`;
});
// Highlight annotations
highlighted = highlighted.replace(/^(\s*@\w+(?:\([^)]*\))?)/gm, '<span class="annotation">$1</span>');
// Highlight import statements
highlighted = highlighted.replace(/\b(import)\s+(.+)/g, '<span class="keyword">$1</span> <span class="import">$2</span>');
// Highlight package statements
highlighted = highlighted.replace(/\b(package)\s+(.+)/g, '<span class="keyword">$1</span> <span class="package">$2</span>');
// Highlight generics
highlighted = highlighted.replace(/<(\w+(?:<[^>]*>)?)>/g, '<span class="generic"><$1></span>');
// Highlight lambda expressions
highlighted = highlighted.replace(/\b(\w+)\s*->/g, '<span class="lambda">$1</span> ->');
// Highlight try-with-resources
highlighted = highlighted.replace(/\b(try)\s*\(/g, '<span class="keyword">$1</span>(');
return highlighted;
}
runCode() {
if (!this.currentFile) {
this.showOutput('No file open to run', 'error');
return;
}
const file = this.files.get(this.currentFile);
if (!file) return;
this.showOutput(`Running ${this.currentFile}...`, 'info');
if (file.language === 'python') {
this.runPythonCode(file.content);
} else if (file.language === 'java') {
this.showOutput('Java compilation and execution would happen here in a real environment.', 'info');
this.showOutput('For now, you can copy the code to your local Java development environment.', 'info');
} else {
this.showOutput(`Running ${file.language} code...`, 'info');
this.showOutput('Code execution is simulated for this demo.', 'info');
}
}
runPythonCode(code) {
try {
// This is a simplified Python execution simulation
// In a real environment, you'd need a backend service or WebAssembly-based Python runtime
// Simulate execution by parsing and analyzing the code
const lines = code.split('\n');
let output = [];
for (let line of lines) {
line = line.trim();
if (line.startsWith('print(') && line.endsWith(')')) {
const content = line.substring(6, line.length - 1);
if (content.startsWith('"') && content.endsWith('"')) {
output.push(content.substring(1, content.length - 1));
} else if (content.startsWith("'") && content.endsWith("'")) {
output.push(content.substring(1, content.length - 1));
} else {
// Simple variable substitution simulation
if (content.includes('{') && content.includes('}')) {
output.push(content.replace(/\{(\w+)\}/g, (match, varName) => {
// Simple variable lookup simulation
if (varName === 'name') return 'Developer';
if (varName === 'result') return '30';
return match;
}));
} else {
output.push(content);
}
}
} else if (line.includes('for') && line.includes('range(')) {
const rangeMatch = line.match(/range\((\d+)\)/);
if (rangeMatch) {
const count = parseInt(rangeMatch[1]);
for (let i = 0; i < count; i++) {
output.push(`Count: ${i}`);
}
}
}
}
if (output.length > 0) {
this.showOutput('Output:', 'success');
output.forEach(line => this.showOutput(line, 'output'));
} else {
this.showOutput('Code executed successfully (no output)', 'success');
}
} catch (error) {
this.showOutput(`Error: ${error.message}`, 'error');
}
}
showOutput(message, type = 'info') {
const outputContent = document.getElementById('outputContent');
const outputDiv = document.createElement('div');
outputDiv.className = `output-line output-${type}`;
const timestamp = new Date().toLocaleTimeString();
outputDiv.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
outputContent.appendChild(outputDiv);
outputContent.scrollTop = outputContent.scrollHeight;
}
clearOutput() {
document.getElementById('outputContent').innerHTML = `
<div class="welcome-message">
<h3>Output Cleared</h3>
<p>Ready for new output...</p>
</div>
`;
}
setupAutoSave() {
this.autoSaveInterval = setInterval(() => {
this.saveAllFiles();
}, 30000); // Auto-save every 30 seconds
}
setupAutoComplete() {
this.javaCompletions = this.buildJavaCompletions();
this.setupAutoCompleteUI();
}
buildJavaCompletions() {
return {
keywords: [
'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch',
'char', 'class', 'const', 'continue', 'default', 'do', 'double',
'else', 'enum', 'extends', 'final', 'finally', 'float', 'for',
'goto', 'if', 'implements', 'import', 'instanceof', 'int', 'interface',
'long', 'native', 'new', 'package', 'private', 'protected', 'public',
'return', 'short', 'static', 'strictfp', 'super', 'switch',
'synchronized', 'this', 'throw', 'throws', 'transient', 'try',
'void', 'volatile', 'while', 'record', 'sealed', 'permits', 'non-sealed'
],
types: [
'String', 'Integer', 'Double', 'Float', 'Long', 'Short', 'Byte',
'Boolean', 'Character', 'Object', 'Array', 'List', 'Set', 'Map',
'ArrayList', 'HashMap', 'HashSet', 'LinkedList', 'Vector', 'Stack',
'Queue', 'PriorityQueue', 'TreeMap', 'TreeSet', 'LinkedHashMap',
'LinkedHashSet', 'WeakHashMap', 'IdentityHashMap', 'EnumMap',
'ConcurrentHashMap', 'CopyOnWriteArrayList', 'CopyOnWriteArraySet',
'Optional', 'Stream', 'Collector', 'Function', 'Predicate', 'Consumer',
'Supplier', 'BiFunction', 'BiPredicate', 'BiConsumer', 'Runnable',
'Callable', 'Future', 'CompletableFuture', 'Executor', 'ExecutorService'
],
annotations: [
'Override', 'Deprecated', 'SuppressWarnings', 'SafeVarargs',
'FunctionalInterface', 'Native', 'Target', 'Retention', 'Documented',
'Inherited', 'Repeatable', 'SpringBootApplication', 'Component',
'Service', 'Repository', 'Controller', 'Autowired', 'Value',
'Configuration', 'Bean', 'Qualifier', 'Primary', 'Profile'
],
methods: {
'String': [
'length()', 'charAt(int index)', 'substring(int beginIndex)', 'substring(int beginIndex, int endIndex)',
'toLowerCase()', 'toUpperCase()', 'trim()', 'equals(Object obj)', 'equalsIgnoreCase(String anotherString)',
'startsWith(String prefix)', 'endsWith(String suffix)', 'contains(CharSequence s)', 'indexOf(String str)',
'replace(char oldChar, char newChar)', 'replaceAll(String regex, String replacement)', 'split(String regex)'
],
'List': [
'add(E e)', 'add(int index, E element)', 'addAll(Collection<? extends E> c)', 'remove(int index)',
'remove(Object o)', 'get(int index)', 'set(int index, E element)', 'size()', 'isEmpty()', 'clear()',
'contains(Object o)', 'indexOf(Object o)', 'lastIndexOf(Object o)', 'subList(int fromIndex, int toIndex)'
],
'Map': [
'put(K key, V value)', 'get(Object key)', 'remove(Object key)', 'containsKey(Object key)',
'containsValue(Object value)', 'size()', 'isEmpty()', 'clear()', 'keySet()', 'values()', 'entrySet()',
'putAll(Map<? extends K, ? extends V> m)', 'getOrDefault(Object key, V defaultValue)'
],
'Stream': [
'filter(Predicate<? super T> predicate)', 'map(Function<? super T, ? extends R> mapper)',
'flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)', 'distinct()', 'sorted()',
'limit(long maxSize)', 'skip(long n)', 'forEach(Consumer<? super T> action)', 'collect(Collector<? super T, A, R> collector)',
'reduce(T identity, BinaryOperator<T> accumulator)', 'anyMatch(Predicate<? super T> predicate)',
'allMatch(Predicate<? super T> predicate)', 'noneMatch(Predicate<? super T> predicate)', 'count()'
]
},
commonPatterns: [
'public class', 'public interface', 'public enum', 'public record',
'public static void main(String[] args)', 'public static final',
'try { } catch (Exception e) { }', 'try (Resource resource) { }',
'for (int i = 0; i < n; i++)', 'for (String item : items)',
'while (condition)', 'do { } while (condition)',
'if (condition) { } else { }', 'switch (value) { case: break; }',
'List<String> list = new ArrayList<>()', 'Map<String, Object> map = new HashMap<>()',
'Optional<String> optional = Optional.of(value)', 'Stream<String> stream = list.stream()'
]
};
}
setupAutoCompleteUI() {
// Create auto-complete dropdown
const autoCompleteDropdown = document.createElement('div');
autoCompleteDropdown.id = 'autoCompleteDropdown';
autoCompleteDropdown.className = 'auto-complete-dropdown';
autoCompleteDropdown.style.display = 'none';
document.body.appendChild(autoCompleteDropdown);
// Add auto-complete event listener to code editor
const codeEditor = document.getElementById('codeEditor');
codeEditor.addEventListener('input', (e) => {
this.handleAutoComplete(e);
});
codeEditor.addEventListener('keydown', (e) => {
if (e.key === 'Tab' || e.key === 'Enter') {
if (this.isAutoCompleteVisible()) {
this.acceptAutoComplete();
e.preventDefault();
}
} else if (e.key === 'Escape') {
this.hideAutoComplete();
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
if (this.isAutoCompleteVisible()) {
this.navigateAutoComplete(e.key);
e.preventDefault();
}
} else if (e.ctrlKey && e.key === ' ') {
// Manual trigger for auto-complete
e.preventDefault();
this.triggerManualAutoComplete();
}
});
// Hide auto-complete when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('#autoCompleteDropdown') && !e.target.closest('#codeEditor')) {
this.hideAutoComplete();
}
});
}
handleAutoComplete(e) {
if (this.currentLanguage !== 'java') return;
const codeEditor = e.target;
const cursorPos = codeEditor.selectionStart;
const textBeforeCursor = codeEditor.value.substring(0, cursorPos);
// Get the current word being typed
const wordMatch = textBeforeCursor.match(/\b(\w*)$/);
if (!wordMatch) {
this.hideAutoComplete();
return;
}
const currentWord = wordMatch[1];
if (currentWord.length < 2) {
this.hideAutoComplete();
return;
}
// Get suggestions based on context
const suggestions = this.getJavaSuggestions(currentWord, textBeforeCursor);
if (suggestions.length > 0) {
this.showAutoComplete(suggestions, currentWord);
} else {
this.hideAutoComplete();
}
}
getJavaSuggestions(currentWord, textBeforeCursor) {
const suggestions = [];
const lowerWord = currentWord.toLowerCase();
// Add keywords
this.javaCompletions.keywords.forEach(keyword => {
if (keyword.toLowerCase().startsWith(lowerWord)) {
suggestions.push({ text: keyword, type: 'keyword', description: 'Java keyword' });
}
});
// Add types
this.javaCompletions.types.forEach(type => {
if (type.toLowerCase().startsWith(lowerWord)) {
suggestions.push({ text: type, type: 'type', description: 'Java type' });
}
});
// Add annotations
this.javaCompletions.annotations.forEach(annotation => {
if (annotation.toLowerCase().startsWith(lowerWord)) {
suggestions.push({ text: annotation, type: 'annotation', description: 'Java annotation' });
}
});
// Add common patterns
this.javaCompletions.commonPatterns.forEach(pattern => {
if (pattern.toLowerCase().includes(lowerWord)) {
suggestions.push({ text: pattern, type: 'pattern', description: 'Common Java pattern' });
}
});
// Add method suggestions based on context
this.addMethodSuggestions(suggestions, currentWord, textBeforeCursor);
return suggestions.slice(0, 10); // Limit to 10 suggestions
}
addMethodSuggestions(suggestions, currentWord, textBeforeCursor) {
// Check if we're in a method call context
const methodCallMatch = textBeforeCursor.match(/(\w+)\.(\w*)$/);
if (methodCallMatch) {
const objectName = methodCallMatch[1];
const methodStart = methodCallMatch[2];
// Get methods for common types
Object.keys(this.javaCompletions.methods).forEach(type => {
if (objectName.toLowerCase().includes(type.toLowerCase()) ||
this.isVariableOfType(objectName, type, textBeforeCursor)) {
this.javaCompletions.methods[type].forEach(method => {
if (method.toLowerCase().startsWith(methodStart.toLowerCase())) {