@acepad/files
v1.0.0
Published
File and session management utilities for acepad.
Readme
NOTE: This package is supporsed to work in acepad, not a regular node envronment.
@acepad/files
File and session management utilities for acepad. This package provides core functionality for opening files, managing editor sessions, directory navigation, and recent file tracking in the browser-based programming environment.
Features
- File opening and editing: Open files and directories in the acepad editor
- Session management: Create and manage editor sessions for files and directory listings
- Recent files tracking: LRU-based tracking of recently accessed files with persistent storage
- Directory listings: Interactive directory views with file operations
- Auto-save: Automatic save on every typing.
- Auto-sync: Automatic synchronization between editor content and file system
- Cursor position memory: Remembers cursor position for each file
- Syntax highlighting: Automatic mode detection based on file extensions
- Annotations support: Display annotations (errors, warnings) in editor sessions(currently only in javascript)
Note: This package is designed to run in the acepad/petit-node environment, not in standard Node.js.
Basic Usage
The following stuffs are supporsed to operate in acepad.
Opening Files
The most common operation is opening files for editing. In acepad, files are automatically opened through the UI, but you can also open them programmatically.
From the acepad interface:
- Navigate to a directory listing
- Press Ent(Enter) on a file name to open it
- The file opens in the editor with syntax highlighting
- Changes are automatically saved
From a script (press F2 to create file and F5 to run):
Note: The following programs are generated by AI, not tested :-(
#!run
import {openFile} from "@acepad/files";
export async function main() {
// Open a file in the current directory
await openFile(this, "myfile.js");
// Open a file with specific cursor position
await openFile(this, "config.json", {row: 10, column: 5});
// Open a directory (shows directory listing)
await openFile(this, "./mydir/");
}Working with Recent Files
Access your recently opened files:
#!run
import {recents} from "@acepad/files";
export async function main() {
// Get list of recent files
const recentFiles = recents.list();
for (let filePath of recentFiles) {
this.echo(filePath);
}
// Add a file to recents
const file = this.resolve("important.txt");
recents.add(this, file);
}In the acepad interface:
- Press F1 to open the recent files list
- Use arrow keys to navigate
- Press Enter to open a file
Getting the Current File
Find out which file is currently being edited:
#!run
import {current} from "@acepad/files";
export async function main() {
const currentFile = current(this);
this.echo(`Currently editing: ${currentFile.path()}`);
this.echo(`File size: ${currentFile.size()} bytes`);
}Developer Guide
Core API
openFile(sh, fileOrPath, options?)
Opens a file or directory in the editor.
Parameters:
sh- Shell object (typicallythisin a command), see @acepad/shell for details.fileOrPath- File path string or SFile objectoptions- Optional settings:row- Cursor row position (1-based)column- Cursor column position (0-based)
Returns: Editor session object
Example:
import {openFile} from "@acepad/files";
// Open file at specific position
await openFile(sh, "/home/user/code.js", {row: 15, column: 8});
// Open using SFile object
const file = sh.resolve("README.md");
await openFile(sh, file);Behavior:
- If the file is already open in a session, switches to that session
- For directories, creates an interactive directory listing
- Creates new files if they don't exist
- Restores previous cursor position if no position specified
- Adds file to recent files list
- Sets syntax highlighting mode based on file extension
current(sh)
Returns the SFile object of the currently edited file.
Parameters:
sh- Shell object
Returns: SFile object or undefined
Example:
import {current} from "@acepad/files";
const file = current(sh);
if (file) {
console.log(`Editing: ${file.name()}`);
}createDirList(sh, directory)
Creates an interactive directory listing session.
Parameters:
sh- Shell objectdirectory- SFile object pointing to a directory
Returns: Editor session object
Features of directory listings:
- Shows files sorted by last modified time
- Parent directory link (
../) new:prompt for creating files/directoriessh:prompt for executing shell commands- Recent shell command history for the directory
- Keyboard shortcuts:
F6- Refresh listingF7- Open parent directoryCtrl+T- Rename fileCtrl+E- Remove fileEnter- Open file/execute command
Example:
import {createDirList} from "@acepad/files";
const dir = sh.resolve("/home/user/projects/");
const session = createDirList(sh, dir);
// The session is automatically displayed in the editorcreateSessionListWithRecents(sh)
Creates a session list showing both open sessions and recent files.
Parameters:
sh- Shell object
Returns: Editor session object
Features:
- Shows currently open editor sessions
- Lists recently accessed files (excluding already open ones)
- Automatically removes duplicate entries
- Keyboard shortcuts:
Enter- Open selected file/sessionF7- Open most recent file
Example:
import {createSessionListWithRecents} from "@acepad/files";
const listSession = createSessionListWithRecents(sh);
// Press F1 in acepad to see this viewfindSessionByFile(file)
Finds an editor session for a given file.
Parameters:
file- SFile object
Returns: Editor session object or undefined
Example:
import {findSessionByFile} from "@acepad/files";
const file = sh.resolve("config.json");
const session = findSessionByFile(file);
if (session) {
console.log("File is already open");
} else {
console.log("File is not open");
}Recent Files API
The recents module manages the recent files list with LRU (Least Recently Used) caching.
recents.list()
Returns array of recent file paths.
import {recents} from "@acepad/files";
const files = recents.list();
// Returns: ["/path/to/file1.js", "/path/to/dir/", ...]recents.add(sh, file)
Adds a file to the recent files list.
Parameters:
sh- Shell objectfile- SFile object
import {recents} from "@acepad/files";
const file = sh.resolve("important.txt");
recents.add(sh, file);Behavior:
- Maintains LRU order (most recent first)
- Limits list to 36 entries
- Persists to
.acepad/recents.json - Updates submenu data for UI shortcuts
recents.read()
Reads the raw recent files data structure.
Returns: Lru object containing recent files
import {recents} from "@acepad/files";
const lru = recents.read();
for (let entry of lru) {
console.log(entry.path);
}Cursor Position Memory
The pos module automatically saves and restores cursor positions.
pos.get(file)
Gets the saved cursor position for a file.
Parameters:
file- SFile object
Returns: Object with {row, column} (defaults to {row: 1, column: 1})
pos.set(file, {row, column})
Saves cursor position for a file.
Parameters:
file- SFile object- Position object with
rowandcolumn
Storage: Positions are stored in .meta/[dir-path]/pos.json
Auto-sync Functionality
The auto-sync system keeps editor content and file system in sync.
import {init as initAutoSync} from "@acepad/files/autoSync.js";
// Initialize auto-sync for an editor
// (This is called automatically by openFile)
initAutoSync(editor);Behavior:
- Checks every 100ms for changes
- If file changes on disk, updates editor content
- If editor content changes, writes to file
- Tracks file timestamps to detect external changes
Annotations
Display errors, warnings, or other annotations in the editor.
import {setAnnotations} from "@acepad/files";
// Set annotations for files
await setAnnotations([
{
file: sh.resolve("code.js"),
row: 5,
column: 10,
text: "Undefined variable",
type: "error"
},
{
file: sh.resolve("code.js"),
row: 12,
column: 0,
text: "Unused parameter",
type: "warning"
}
]);Annotation types:
error- Red markerwarning- Yellow markerinfo- Blue marker
File Extension to Mode Mapping
The package includes built-in syntax highlighting for common file types:
import {modeMap} from "@acepad/files";
// View supported extensions
console.log(modeMap);
// {
// ".js": "ace/mode/javascript",
// ".html": "ace/mode/html",
// ".py": "ace/mode/python",
// ...
// }Supported file types:
- JavaScript:
.js,.cjs,.mjs - TypeScript:
.ts - HTML:
.html - CSS:
.css - JSON:
.json - Python:
.py - C:
.c - PHP:
.php - Tonyu:
.tonyu
Files starting with #!run or //!run automatically use JavaScript mode.
Advanced Examples
Creating a File Browser
#!run
import {openFile, createDirList} from "@acepad/files";
export async function main() {
const projectDir = this.resolve("/home/user/projects/");
if (!projectDir.exists()) {
projectDir.mkdir();
}
// Open directory browser
await openFile(this, projectDir);
}File Navigator with Search
#!run
import {recents, openFile} from "@acepad/files";
export async function main(searchTerm) {
const recentFiles = recents.list();
// Search in recent files
const matches = recentFiles.filter(path =>
path.includes(searchTerm)
);
if (matches.length === 0) {
this.echo("No matches found");
return;
}
if (matches.length === 1) {
// Open directly if only one match
await openFile(this, matches[0]);
} else {
// Show matches
this.echo("Multiple matches:");
matches.forEach((path, i) => {
this.echo(`${i + 1}. ${path}`);
});
}
}Session Management Tool
#!run
import {findSessionByFile} from "@acepad/files";
import {recentInfos} from "@acepad/sessions";
export async function main() {
this.echo("Currently open sessions:");
let count = 0;
for (let si of recentInfos()) {
if (si.file) {
this.echo(` ${si.name} - ${si.file.path()}`);
count++;
}
}
this.echo(`Total: ${count} sessions`);
}Working with Cursor Positions
#!run
import * as pos from "@acepad/files/pos.js";
export async function main() {
const file = this.resolve("mycode.js");
// Save a bookmark
pos.set(file, {row: 42, column: 0});
this.echo("Bookmark saved at line 42");
// Later, retrieve the bookmark
const bookmark = pos.get(file);
this.echo(`Bookmark: line ${bookmark.row}, column ${bookmark.column}`);
}Directory Structure
@acepad/files/
├── acepad-files.js # Main module with file/session operations
├── recents.js # Recent files tracking (also a command)
├── pos.js # Cursor position memory
├── autoSync.js # Auto-sync between editor and file system
├── annotations.js # Annotation support
├── package.json # Package metadata
└── test/
└── test-acepad-files.jsStorage Locations
The package uses the following directories for persistent data:
- Recent files:
.acepad/recents.json(in PNODE_ROOT or detected root) - Submenu cache:
.acepad/submenus.json - Cursor positions:
.meta/[directory]/pos.json(per directory)
These files are automatically created and managed by the package.
Command-line Tool
The package includes a recents command that can be run from the shell:
sh: recentsThis displays all recent files and can be used to quickly navigate to them using the edit command.
Integration with acepad
This package is a core component of acepad and integrates with:
- @acepad/shell: File operations and command execution
- @acepad/sessions: Editor session management
- @acepad/cursor: Cursor position tracking
- @acepad/mode-shell: Shell mode for directory listings
- ace editor: Underlying code editor
Dependencies
petit-node: Browser-based Node.js runtime@acepad/shell: Shell environment@acepad/sessions: Session management@acepad/cursor: Cursor utilities@acepad/mode-shell: Shell syntax mode@acepad/os: OS utilities@acepad/here: Path resolution@hoge1e3/lru: LRU cache implementationtextmatcher: Text pattern matching@acepad/retry: Retry utilities@acepad/debug: Debug utilities
License
ISC
See Also
- acepad - The acepad programming environment
- @acepad/shell - Shell command system
- petit-node - Browser-based Node.js runtime
