Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions commands/edit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
description: Edit an existing Apple Note
allowed-tools: Bash(notes:*)
argument-hint: <id> --body "new content" [--folder "Folder"]
---

# Edit Note

Edit an existing note in Apple Notes. The created timestamp is preserved.

## Instructions

1. Check if the notes CLI is installed:
```bash
command -v notes || pnpm add -g @cardmagic/notes
```

2. Edit the note:
```bash
notes edit $ARGUMENTS
```

## Examples

- `/notes:edit 123 --body "Updated content"` - Edit note by ID
- `/notes:edit --title "Meeting Notes" --body "New agenda"` - Edit by title
- `/notes:edit --title "Todo" --body "New tasks" --folder "Work"` - Edit with folder disambiguation

## Workflow

1. Find the note: `notes search "keyword"` or `notes recent`
2. Read current content: `notes read <id>`
3. Edit the note: `notes edit <id> --body "new content"`
176 changes: 137 additions & 39 deletions src/applescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,100 @@ export interface DeleteNoteResult {
name: string;
}

export interface EditNoteOptions {
title: string;
body: string;
folder?: string;
}

export interface EditNoteResult {
success: boolean;
name: string;
folder: string;
}

/**
* Escapes a string for safe use in AppleScript string literals.
* Handles backslashes, quotes, newlines, and control characters.
*/
function escapeAppleScript(str: string): string {
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
return str
.replace(/\\/g, '\\\\') // Backslash must be first
.replace(/"/g, '\\"') // Double quotes
.replace(/\n/g, '\\n') // Newlines
.replace(/\r/g, '\\r') // Carriage returns
.replace(/\t/g, '\\t') // Tabs
.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F]/g, ''); // Strip other control chars
}

function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

/**
* Executes an AppleScript by passing it via stdin to avoid shell injection.
* This is more secure than using -e flag with shell escaping.
*
* @param script - The complete AppleScript to execute
* @returns The output from the script
* @throws Error if execution fails
*/
function executeAppleScript(script: string): string {
return execSync('osascript -', {
input: script,
encoding: 'utf-8',
timeout: 30000,
maxBuffer: 10 * 1024 * 1024, // 10MB for large note bodies
});
}

/**
* Builds an AppleScript that finds a note by title and performs an operation on it.
* Handles folder scoping when provided.
*
* @param title - The note title to search for
* @param operation - AppleScript code to execute on the found note. The note is available
* as the `targetNote` variable. Should include a `return` statement.
* Example: `delete targetNote\nreturn "deleted"`
* @param folder - Optional folder name to scope the search
*/
function buildNoteOperationScript(
title: string,
operation: string,
folder?: string
): string {
const escapedTitle = escapeAppleScript(title);

if (folder) {
const escapedFolder = escapeAppleScript(folder);
return `
tell application "Notes"
set targetFolder to folder "${escapedFolder}"
set matchingNotes to notes of targetFolder whose name is "${escapedTitle}"
if (count of matchingNotes) is 0 then
error "Note not found"
end if
set targetNote to item 1 of matchingNotes
${operation}
end tell
`;
} else {
return `
tell application "Notes"
set matchingNotes to notes whose name is "${escapedTitle}"
if (count of matchingNotes) is 0 then
error "Note not found"
end if
set targetNote to item 1 of matchingNotes
${operation}
end tell
`;
}
}

export function createNote(options: CreateNoteOptions): CreateNoteResult {
Expand All @@ -37,10 +129,7 @@ export function createNote(options: CreateNoteOptions): CreateNoteResult {
`;

try {
const result = execSync(`osascript -e '${script.replace(/'/g, "'\"'\"'")}'`, {
encoding: 'utf-8',
timeout: 30000,
});
const result = executeAppleScript(script);

return {
success: true,
Expand All @@ -58,44 +147,56 @@ export function createNote(options: CreateNoteOptions): CreateNoteResult {

export function deleteNote(title: string, folder?: string): DeleteNoteResult {
const escapedTitle = escapeAppleScript(title);
const operation = `
delete targetNote
return "${escapedTitle}"
`;

let script: string;
const script = buildNoteOperationScript(title, operation, folder);

if (folder) {
const escapedFolder = escapeAppleScript(folder);
script = `
tell application "Notes"
set targetFolder to folder "${escapedFolder}"
set matchingNotes to notes of targetFolder whose name is "${escapedTitle}"
if (count of matchingNotes) is 0 then
error "Note not found"
end if
delete item 1 of matchingNotes
return "${escapedTitle}"
end tell
`;
} else {
script = `
tell application "Notes"
set matchingNotes to notes whose name is "${escapedTitle}"
if (count of matchingNotes) is 0 then
error "Note not found"
end if
delete item 1 of matchingNotes
return "${escapedTitle}"
end tell
`;
try {
const result = executeAppleScript(script);

return {
success: true,
name: result.trim(),
};
} catch (error) {
const message = (error as Error).message;
if (message.includes('Note not found')) {
const folderInfo = folder ? ` in folder "${folder}"` : '';
throw new Error(`Note "${title}" not found${folderInfo}.`);
}
if (message.includes('get folder')) {
throw new Error(`Folder "${folder}" not found. Use 'notes folders' to list available folders.`);
}
throw new Error(`Failed to delete note: ${message}`);
}
}

export function editNote(options: EditNoteOptions): EditNoteResult {
const { title, body, folder } = options;

// Apple Notes uses the first line of the body as the title, so we prepend the title
// as an HTML heading to preserve it when setting the body
const fullBody = `<h1>${escapeHtml(title)}</h1><br>${escapeHtml(body)}`;
const escapedBody = escapeAppleScript(fullBody);
const targetFolder = folder || 'Notes';

const operation = `
set body of targetNote to "${escapedBody}"
return name of targetNote
`;

const script = buildNoteOperationScript(title, operation, folder);

try {
const result = execSync(`osascript -e '${script.replace(/'/g, "'\"'\"'")}'`, {
encoding: 'utf-8',
timeout: 30000,
});
const result = executeAppleScript(script);

return {
success: true,
name: result.trim(),
folder: targetFolder,
};
} catch (error) {
const message = (error as Error).message;
Expand All @@ -106,7 +207,7 @@ export function deleteNote(title: string, folder?: string): DeleteNoteResult {
if (message.includes('get folder')) {
throw new Error(`Folder "${folder}" not found. Use 'notes folders' to list available folders.`);
}
throw new Error(`Failed to delete note: ${message}`);
throw new Error(`Failed to edit note: ${message}`);
}
}

Expand All @@ -123,10 +224,7 @@ export function listNoteFolders(): string[] {
`;

try {
const result = execSync(`osascript -e '${script.replace(/'/g, "'\"'\"'")}'`, {
encoding: 'utf-8',
timeout: 30000,
});
const result = executeAppleScript(script);

return result.trim().split('\n').filter(Boolean);
} catch (error) {
Expand Down
57 changes: 56 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
formatIndexProgress,
formatNote,
} from './formatter.js';
import { createNote, deleteNote } from './applescript.js';
import { createNote, deleteNote, editNote } from './applescript.js';

const program = new Command();

Expand Down Expand Up @@ -224,6 +224,61 @@ program
}
});

program
.command('edit [id]')
.description('Edit an existing note by ID or title (ID takes precedence if both provided)')
.option('-t, --title <name>', 'Edit by title instead of ID')
.option('-b, --body <text>', 'New body content')
.option('-f, --folder <name>', 'Folder containing the note (for disambiguation)')
.action(async (id: string | undefined, options: { title?: string; body?: string; folder?: string }) => {
try {
if (!options.body) {
console.error('Error: --body is required');
process.exit(1);
}

if (!id && !options.title) {
console.error('Error: Either <id> or --title is required');
process.exit(1);
}

let title: string;
let folder: string | undefined = options.folder;

// ID takes precedence if both are provided
if (id) {
const noteId = parseInt(id, 10);
if (isNaN(noteId)) {
console.error('Invalid note ID');
process.exit(1);
}

const note = await getNoteById(noteId);
if (!note) {
console.error('Note not found');
process.exit(1);
}

title = note.title;
folder = folder || note.folder;
} else {
title = options.title!;
}

const result = editNote({
title,
body: options.body,
folder,
});
Comment on lines +268 to +272
Copy link

Copilot AI Feb 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The editNote() call is not awaited, but it executes a synchronous operation via execSync. Consider making editNote async and awaiting it here for consistency with other async operations in this action handler, or document why synchronous execution is intentional.

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following the pattern of other commands like create and delete

console.log(`Updated note "${result.name}" in folder "${result.folder}"`);
} catch (error) {
console.error('Error:', (error as Error).message);
process.exit(1);
} finally {
closeConnections();
}
});

export function runCli(): void {
program.parse(process.argv);
}
Loading