forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmodelist.ts
More file actions
258 lines (223 loc) · 5.94 KB
/
modelist.ts
File metadata and controls
258 lines (223 loc) · 5.94 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
import type { Extension } from "@codemirror/state";
export type LanguageExtensionProvider = () => Extension | Promise<Extension>;
export interface AddModeOptions {
aliases?: string[];
filenameMatchers?: RegExp[];
}
export interface ModesByName {
[name: string]: Mode;
}
const modesByName: ModesByName = {};
const modes: Mode[] = [];
function normalizeModeKey(value: string): string {
return String(value ?? "")
.trim()
.toLowerCase();
}
function normalizeAliases(aliases: string[] = [], name: string): string[] {
const normalized = new Set<string>();
for (const alias of aliases) {
const key = normalizeModeKey(alias);
if (!key || key === name) continue;
normalized.add(key);
}
return [...normalized];
}
function escapeRegExp(value: string): string {
return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Initialize CodeMirror mode list functionality
*/
export function initModes(): void {
// CodeMirror modes don't need the same ace.define wrapper
// but we maintain the same API structure for compatibility
}
/**
* Add language mode to CodeMirror editor
*/
export function addMode(
name: string,
extensions: string | string[],
caption?: string,
languageExtension: LanguageExtensionProvider | null = null,
options: AddModeOptions = {},
): void {
const filename = normalizeModeKey(name);
const mode = new Mode(
filename,
caption,
extensions,
languageExtension,
options,
);
modesByName[filename] = mode;
mode.aliases.forEach((alias) => {
if (!modesByName[alias]) {
modesByName[alias] = mode;
}
});
modes.push(mode);
}
/**
* Remove language mode from CodeMirror editor
*/
export function removeMode(name: string): void {
const filename = normalizeModeKey(name);
const mode = modesByName[filename];
if (!mode) return;
delete modesByName[mode.name];
mode.aliases.forEach((alias) => {
if (modesByName[alias] === mode) {
delete modesByName[alias];
}
});
const modeIndex = modes.findIndex(
(registeredMode) => registeredMode === mode,
);
if (modeIndex >= 0) {
modes.splice(modeIndex, 1);
}
}
/**
* Get mode for file path
*/
export function getModeForPath(path: string): Mode {
let mode = modesByName.text;
const fileName = path.split(/[/\\]/).pop() || "";
// Sort modes by specificity (descending) to check most specific first
const sortedModes = [...modes].sort((a, b) => {
return getModeSpecificityScore(b) - getModeSpecificityScore(a);
});
for (const iMode of sortedModes) {
if (iMode.supportsFile?.(fileName)) {
mode = iMode;
break;
}
}
return mode;
}
/**
* Calculates a specificity score for a mode.
* Higher score means more specific.
* - Anchored patterns (e.g., "^Dockerfile") get a base score of 1000.
* - Non-anchored patterns (extensions) are scored by length.
*/
function getModeSpecificityScore(modeInstance: Mode): number {
const extensionsStr = modeInstance.extensions;
let maxScore = 0;
if (extensionsStr) {
const patterns = extensionsStr.split("|");
for (const pattern of patterns) {
let currentScore = 0;
if (pattern.startsWith("^")) {
// Exact filename match or anchored pattern
currentScore = 1000 + (pattern.length - 1); // Subtract 1 for '^'
} else {
// Extension match
currentScore = pattern.length;
}
if (currentScore > maxScore) {
maxScore = currentScore;
}
}
}
for (const matcher of modeInstance.filenameMatchers) {
const score = 1000 + matcher.source.length;
if (score > maxScore) {
maxScore = score;
}
}
return maxScore;
}
/**
* Get all modes by name
*/
export function getModesByName(): ModesByName {
return modesByName;
}
/**
* Get all modes array
*/
export function getModes(): Mode[] {
return modes;
}
export function getMode(name: string): Mode | null {
return modesByName[normalizeModeKey(name)] || null;
}
export class Mode {
extensions: string;
caption: string;
name: string;
mode: string;
aliases: string[];
extRe: RegExp | null;
filenameMatchers: RegExp[];
languageExtension: LanguageExtensionProvider | null;
constructor(
name: string,
caption: string | undefined,
extensions: string | string[],
languageExtension: LanguageExtensionProvider | null = null,
options: AddModeOptions = {},
) {
if (Array.isArray(extensions)) {
extensions = extensions.join("|");
}
this.name = name;
this.mode = name; // CodeMirror uses different mode naming
this.extensions = extensions;
this.caption = caption || this.name.replace(/_/g, " ");
this.aliases = normalizeAliases(options.aliases, this.name);
this.filenameMatchers = Array.isArray(options.filenameMatchers)
? options.filenameMatchers.filter((matcher) => matcher instanceof RegExp)
: [];
this.languageExtension = languageExtension;
let re = "";
if (!extensions) {
this.extRe = null;
return;
}
const patterns = extensions
.split("|")
.map((pattern) => pattern.trim())
.filter(Boolean);
const filenamePatterns = patterns
.filter((pattern) => pattern.startsWith("^"))
.map((pattern) => `^${escapeRegExp(pattern.slice(1))}$`);
const extensionPatterns = patterns
.filter((pattern) => !pattern.startsWith("^"))
.map((pattern) => escapeRegExp(pattern));
const regexParts: string[] = [];
if (extensionPatterns.length) {
regexParts.push(`^.*\\.(${extensionPatterns.join("|")})$`);
}
regexParts.push(...filenamePatterns);
if (!regexParts.length) {
this.extRe = null;
return;
}
re =
regexParts.length === 1 ? regexParts[0] : `(?:${regexParts.join("|")})`;
this.extRe = new RegExp(re, "i");
}
supportsFile(filename: string): boolean {
if (this.extRe?.test(filename)) return true;
return this.filenameMatchers.some((matcher) => {
matcher.lastIndex = 0;
return matcher.test(filename);
});
}
/**
* Get the CodeMirror language extension
*/
getExtension(): LanguageExtensionProvider | null {
return this.languageExtension;
}
/**
* Check if the language extension is available (loaded)
*/
isAvailable(): boolean {
return this.languageExtension !== null;
}
}