Editor File API
The Editor File API provides functionality to create, manage, interact with files/tabs in the Acode editor. It handles file operations, state management, editor session control, custom editor tab, etc.
TIP
This API is defined in the Acode source code (src/lib/editorFile.js).
Import
const EditorFile = acode.require('editorFile');Constructor
new EditorFile(filename, options)INFO
You can also use acode.newEditorFile(filename, options) as an alternative. Both methods are equivalent and accept & return the same parameters.
Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
| filename | string | Name of the file | - |
| options | FileOptions | File creation options | - |
FileOptions
| Property | Type | Description | Default |
|---|---|---|---|
| isUnsaved | boolean | Whether file needs to be saved | false |
| render | boolean | Make file active | true |
| id | string | ID for the file | - |
| uri | string | URI of the file | - |
| text | string | Session text | - |
| editable | boolean | Enable file editing | true |
| deletedFile | boolean | File does not exist at source | false |
| SAFMode | 'single' | 'tree' | Storage access framework mode | - |
| encoding | string | Text encoding | appSettings.value.defaultFileEncoding |
| cursorPos | object | Cursor position | - |
| scrollLeft | number | Scroll left position | - |
| scrollTop | number | Scroll top position | - |
| folds | Array<{ fromLine: number, fromCol: number, toLine: number, toCol: number }> | Code folds | - |
| type | string | Type of content (e.g., 'editor') | 'editor' |
| tabIcon | string | Icon class for the file tab | 'file file_type_default' |
| content | string | HTMLElement | Custom content element or HTML string. Strings are sanitized using DOMPurify | - |
| stylesheets | string|string[] | Custom stylesheets for tab. Can be URL, or CSS string | - |
| highlightStyles | boolean | Adopt the static CodeMirror highlight stylesheet into this custom tab's shadow root. Use only when the tab will render codeHighlight HTML. Available from versionCode 1008 | false |
| hideQuickTools | boolean | Whether to hide quicktools for this tab | false |
| pinned | boolean | Pin the tab to prevent accidental closing | false |
| readOnly | boolean | Open the file as read-only | false |
| paneId | string | Target editor pane id (multi-pane layout) | - |
| pane | object | Target editor pane instance (multi-pane layout) | - |
| isPanePlaceholder | boolean | Temporary empty tab for an empty pane | false |
Properties
Read-only Properties
| Property | Type | Description |
|---|---|---|
| type | string | Type of content this file represents |
| tabIcon | string | Icon class for the file tab |
| content | HTMLElement | Custom content element |
| id | string | File unique ID |
| filename | string | Name of the file |
| location | string | Directory path of the file |
| uri | string | File location on the device |
| eol | 'windows' | 'unix' | End of line character |
| editable | boolean | Whether file can be edited |
| pinned | boolean | Whether the file is pinned |
| isUnsaved | boolean | Whether file has unsaved changes |
| name | string | File name (for plugin compatibility) |
| cacheFile | string | Cache file URL |
| icon | string | File icon class |
| tab | HTMLElement | File tab element |
| SAFMode | 'single' | 'tree' | null | Storage access framework mode |
| loaded | boolean | Whether file has completed loading text |
| loading | boolean | Whether file is still loading text |
| session | Proxy<EditorState> | Session state with Ace-compatible helper methods |
| readOnly | boolean | Whether file is readonly |
| markChanged | boolean | Whether to mark changes when session text changes |
Writable(setters) Properties
| Property | Type | Description |
|---|---|---|
| id | string | Set file unique ID |
| filename | string | Set file name |
| location | string | Set file directory path |
| uri | string | Set file location |
| eol | 'windows' | 'unix' | Set end of line character |
| editable | boolean | Set file editability |
| pinned | boolean | Set file pinned state |
| readOnly | boolean | Set file readonly state |
Methods
File Operations
save()
Saves the file to its current location.
await file.save();saveAs()
Saves the file to a new location.
await file.saveAs();remove(force = false, options = { ignorePinned = false, silentPinned = false })
Removes and closes the file.
await file.remove(true); // Force close without save prompt
// Attempt to close a pinned tab, bypassing the pinned check
// Attempt to close a pinned tab, bypassing the pinned check
await file.remove(false, { ignorePinned: true });
// Attempt to close a pinned tab silently (toast suppressed)
await file.remove(false, { silentPinned: true });makeActive()
Makes this file the active file in the editor.
file.makeActive();removeActive()
Removes active state from the file.
file.removeActive();setPinnedState(value: boolean, options = { reorder = false, emit = true })
Updates Pinned State for the file, triggers reorder (if true), emits Events (editorManager update event with pin-tab as the first argument and affected File - second argument )
file.setPinnedState(false, {})
editorManager.on("update", (action, file) => {
if(action === "pin-tab") doSomething();
});togglePinned()
Toggles the pinned State of the file
file.togglePinned();Editor Operations
setMode(mode)
Sets syntax highlighting mode for the file.
file.setMode('javascript');writeToCache()
Writes file content to cache.
await file.writeToCache();isChanged()
Checks if file has unsaved changes.
const changed = await file.isChanged();canRun()
Checks if file can be run.
const canRun = await file.canRun();writeCanRun(callback)
Sets whether to show run button.
file.writeCanRun(() => true);run()
Runs the file.
file.run();runFile()
Runs the file in app.
file.runFile();openWith()
Opens file with system app.
file.openWith();editWith()
Opens file for editing with system app.
file.editWith();share()
Shares the file.
file.share();addStyle(style)
Adds stylesheet to tab's shadow DOM.
file.addStyle('custom.css');Event Handling
on(event, callback)
Adds event listener.
file.on('save', (event) => {
console.log('File saved');
});off(event, callback)
Removes event listener.
file.off('save', callback);Events
The EditorFile class emits the following events:
| Event | Description |
|---|---|
| save | File is saved |
| change | File content changes |
| focus | File gains focus |
| blur | File loses focus |
| close | File is closed |
| rename | File is renamed |
| load | File is loaded |
| loadError | Error loading file |
| loadStart | File loading starts |
| loadEnd | File loading ends |
| changeMode | Syntax mode changes |
| run | File is run |
| canRun | File runnable state changes |
Examples
Creating a New File
const file = new EditorFile('example.js', {
text: 'console.log("Hello World");',
editable: true
});Creating a Custom File Type
// Method 1: Using HTML string
const file1 = new EditorFile('custom.html', {
type: 'custom',
content: '<div class="custom-content"><h1>Custom Content</h1></div>',
stylesheets: [
// External stylesheet
'https://example.com/styles.css',
// Local stylesheet
'/styles/custom.css',
// Inline CSS
`
.custom-content {
padding: 20px;
background: #f5f5f5;
}
`
],
hideQuickTools: true
});
// Method 2: Using HTMLElement
const customElement = document.createElement('div');
customElement.innerHTML = '<h1>Custom Content</h1>';
const file2 = new EditorFile('custom.html', {
type: 'custom',
content: customElement,
stylesheets: ['/styles/custom.css'],
hideQuickTools: true
});
// Add additional styles later if needed
file1.addStyle('/styles/additional.css');WARNING
Custom Editor Tabs are isolated from main DOM using Shadow DOM, so don't select tab elements using document.
Syntax highlighting inside a custom tab is opt-in and available from versionCode 1008. Set highlightStyles: true so the tab's shadow root gets the theme stylesheet, then add the cm-highlighted class to the wrapper. See Code Highlight.
const codeHighlight = acode.require("codeHighlight");
const html = await codeHighlight.highlightCodeBlock(source, "javascript");
const code = document.createElement("code");
code.className = codeHighlight.HIGHLIGHT_CLASS;
code.innerHTML = html;
new EditorFile("snippet.js", {
type: "custom",
content: code,
highlightStyles: true,
hideQuickTools: true,
});Saving File Changes
try {
await file.save();
console.log('File saved successfully');
} catch (err) {
console.error('Error saving file:', err);
}Saving a Custom Tab v1012+
A custom tab gets Acode's normal save controls (the save button, Ctrl + S and the Save command) once it has a save listener. In the listener, call event.respondWith() synchronously with a promise that resolves to true after your data is written. event.saveAs is true for Save as.
const fs = acode.require('fs');
const tab = new EditorFile('data.json', { type: 'custom', content: element });
tab.on('save', (event) => {
event.respondWith(
(async () => {
await fs(fileUrl).writeFile(JSON.stringify(myData));
tab.isUnsaved = false;
return true;
})()
);
});
// Mark the tab as changed so it shows the unsaved indicator.
tab.isUnsaved = true;respondWith() can be called only once per save. Resolving to anything other than true tells Acode the save didn't happen. For plugin editors that also need QuickTools input, see QuickTools Adapter.
Handling File Events
file.on('change', (event) => {
console.log('File content changed');
});
file.on('save', (event) => {
console.log('File saved');
});Running a File
if (await file.canRun()) {
file.run();
}Error Handling
The API includes built-in error handling for file operations. Always wrap async operations in try/catch blocks:
try {
await file.save();
} catch (err) {
console.error('Error saving file:', err);
}TIP
Use the isChanged() method to check for unsaved changes before closing files.
WARNING
Always handle file operations asynchronously and implement proper error handling.
