Skip to content

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

js
const EditorFile = acode.require('editorFile');

Constructor

js
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

ParameterTypeDescriptionDefault
filenamestringName of the file-
optionsFileOptionsFile creation options-

FileOptions

PropertyTypeDescriptionDefault
isUnsavedbooleanWhether file needs to be savedfalse
renderbooleanMake file activetrue
idstringID for the file-
uristringURI of the file-
textstringSession text-
editablebooleanEnable file editingtrue
deletedFilebooleanFile does not exist at sourcefalse
SAFMode'single' | 'tree'Storage access framework mode-
encodingstringText encodingappSettings.value.defaultFileEncoding
cursorPosobjectCursor position-
scrollLeftnumberScroll left position-
scrollTopnumberScroll top position-
foldsArray<Fold>Code folds-
typestringType of content (e.g., 'editor')'editor'
tabIconstringIcon class for the file tab'file file_type_default'
contentstring | HTMLElementCustom content element or HTML string. Strings are sanitized using DOMPurify-
stylesheetsstring|string[]Custom stylesheets for tab. Can be URL, or CSS string-
hideQuickToolsbooleanWhether to hide quicktools for this tabfalse

Properties

Read-only Properties

PropertyTypeDescription
typestringType of content this file represents
tabIconstringIcon class for the file tab
contentHTMLElementCustom content element
idstringFile unique ID
filenamestringName of the file
locationstringDirectory path of the file
uristringFile location on the device
eol'windows' | 'unix'End of line character
editablebooleanWhether file can be edited
isUnsavedbooleanWhether file has unsaved changes
namestringFile name (for plugin compatibility)
cacheFilestringCache file URL
iconstringFile icon class
tabHTMLElementFile tab element
SAFMode'single' | 'tree' | nullStorage access framework mode
loadedbooleanWhether file has completed loading text
loadingbooleanWhether file is still loading text
sessionAceAjax.IEditSessionEditSession of the file
readOnlybooleanWhether file is readonly
markChangedbooleanWhether to mark changes when session text changes

Writable(setters) Properties

PropertyTypeDescription
idstringSet file unique ID
filenamestringSet file name
locationstringSet file directory path
uristringSet file location
eol'windows' | 'unix'Set end of line character
editablebooleanSet file editability
readOnlybooleanSet file readonly state

Methods

File Operations

save()

Saves the file to its current location.

js
await file.save();

saveAs()

Saves the file to a new location.

js
await file.saveAs();

remove(force = false)

Removes and closes the file.

js
await file.remove(true); // Force close without save prompt

makeActive()

Makes this file the active file in the editor.

js
file.makeActive();

removeActive()

Removes active state from the file.

js
file.removeActive();

Editor Operations

setMode(mode)

Sets syntax highlighting mode for the file.

js
file.setMode('javascript');

writeToCache()

Writes file content to cache.

js
await file.writeToCache();

isChanged()

Checks if file has unsaved changes.

js
const changed = await file.isChanged();

canRun()

Checks if file can be run.

js
const canRun = await file.canRun();

writeCanRun(callback)

Sets whether to show run button.

js
file.writeCanRun(() => true);

run()

Runs the file.

js
file.run();

runFile()

Runs the file in app.

js
file.runFile();

openWith()

Opens file with system app.

js
file.openWith();

editWith()

Opens file for editing with system app.

js
file.editWith();

share()

Shares the file.

js
file.share();

addStyle(style)

Adds stylesheet to tab's shadow DOM.

js
file.addStyle('custom.css');

Event Handling

on(event, callback)

Adds event listener.

js
file.on('save', (event) => {
    console.log('File saved');
});

off(event, callback)

Removes event listener.

js
file.off('save', callback);

Events

The EditorFile class emits the following events:

EventDescription
saveFile is saved
changeFile content changes
focusFile gains focus
blurFile loses focus
closeFile is closed
renameFile is renamed
loadFile is loaded
loadErrorError loading file
loadStartFile loading starts
loadEndFile loading ends
changeModeSyntax mode changes
runFile is run
canRunFile runnable state changes

Examples

Creating a New File

js
const file = new EditorFile('example.js', {
    text: 'console.log("Hello World");',
    editable: true
});

Creating a Custom File Type

js
// 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 main DOM(document).

Saving File Changes

js
try {
    await file.save();
    console.log('File saved successfully');
} catch (err) {
    console.error('Error saving file:', err);
}

Handling File Events

js
file.on('change', (event) => {
    console.log('File content changed');
});

file.on('save', (event) => {
    console.log('File saved');
});

Running a File

js
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:

js
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.

Released under the MIT License.