docs/manual/guide/18-user-commands.org

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/docs/manual/guide/18-user-commands.org

329 lines · 30290 bytes

14 symbols in this file

User commands

Overview

A user command is a JavaScript function that reads the buffer it runs in and returns the changes to make. You declare it in commands.toml in the configuration folder and put its code in the commands folder beside it:

~/.config/orgstar/
  commands.toml
  commands/
    headings.js
    review.js

Each command gets the id user.=/name/ and appears wherever commands do: the command palette, =keymap.toml bindings, the Commands list on iPhone and iPad, and [key-bar]. Its changes are one step of undo. User commands are included in every version of orgstar; they don't need orgstar+.

The download version, the Mac App Store version and the iOS app run the same commands with the same API, so a command works unchanged on every device the configuration folder reaches. On iPhone and iPad the folder is the one chosen in Settings (see iPhone and iPad).

commands.toml

api = 1

[[command]]
name = "upcase-title"           # the command user.upcase-title
title = "Upcase Heading Title"  # shown in the palette; default: the name
file = "headings.js"            # in commands/
function = "upcaseTitle"        # an exported function
when = "heading"                # optional; default: everywhere
timeout = 5                     # optional, seconds; default 2, at most 30
workspace = false               # optional; true lets it read your folders and capture

[[command]]
name = "weekly-review"
title = "Add Weekly Review"
file = "review.js"
function = "weeklyReview"
Key Required What it sets
api Yes The API version the commands are written for, at the top of the file. This version of orgstar runs 1.
name Yes Letters, digits, - and _. The command's id is =user.=/name/.
title No The title in the palette, the Commands list and key hints, shown as written.
file Yes A .js or .mjs file in commands/, which may be in a subfolder (lib/dates.js).
function Yes The name of a function the file exports. It may be async.
when No A context from Contexts (heading, table, item, region, …). Where it doesn't hold, the palette and the Commands list leave the command out and its keys fall through.
timeout No Seconds the command may run, 1 to 30; 2 when not given. Time spent waiting for your answer to a prompt doesn't count.
workspace No true lets the command search your folders, read other files' outlines and the agenda, and capture (see Reading your folders and capturing). Default false.

orgstar reads the file without running any code, so commands are listed and bindable before you have run them. It reloads the file, and the list of commands, when the file or anything in commands/ changes; on iPhone and iPad it reloads when the synced folder changes.

Problems are reported like those of the other configuration files (see Problems in the files), and the command with the problem isn't registered:

  • commands.toml: command weekly-review: no file commands/review.js
  • commands.toml: command slow: timeout must be 1 to 30 seconds
  • commands.toml: command review: unknown context headline
  • commands.toml: command find: workspace must be true or false
  • commands.toml: api 2 needs a newer orgstar (no command is registered)
  • commands.toml: missing api = 1 (no command is registered)
  • commands.toml: commands/review.js isn't downloaded from iCloud yet (iPhone and iPad; the download starts)

The commands folder

Files in commands/ are ES modules. They may import each other by relative path (import { pad } from "./lib/text.js") and nothing else: imports from other folders or URLs fail. Each run starts fresh, so nothing a command keeps in a variable survives to its next run, and a changed file is read again.

The function is called with one argument, org, the API below. Its return value says what to change.

The API, version 1

Every call returns a promise; use await. Offsets are UTF-16 code units, as JavaScript strings count them, so text.slice(from, to) gives the text between two offsets.

Call Gives
org.text() The buffer's text: as the command started, or as the last org.run left it.
org.selection() The selections as [{from, to}], the main caret first. With nothing selected, from and to are both the caret. After org.run, where that command left them.
org.heading(at) The heading whose entry holds the offset at (default: the caret), as described below, or null before the first heading.
org.outline() Every heading in the file, in order, as org.heading() describes it.
org.file() The file's path relative to its folder (notes/plan.org), or null for a buffer without a file.
org.settings() todoKeywords, doneKeywords, priorities ({highest, lowest, default}), fileTags, tags (the tags used in your folders), fillColumn and tagsColumn.
org.prompt(options) Asks in the echo area (the Mac) or a sheet (iPhone and iPad) and gives the answer as a string. Throws when you cancel.
org.message(text) Shows text in the echo area while the command runs.
org.fail(text) Ends the command: nothing changes and text is shown. Use it as return org.fail("…").
org.run(id) Runs one of Org's commands by id (org.todo.cycle) and gives the text and selection after it as {text, selection}. See Running Org's commands.
org.search(query) With workspace = true: headings and files in your folders that match query. See Reading your folders and capturing.
org.outlineOf(path) With workspace = true: the headings of another org file in your folders, as org.outline() gives them.
org.agenda({from, to}) With workspace = true: the agenda's entries for a span of days.
org.capture(key, text, fields) With workspace = true: files text with a capture template.
org.version 1.

A heading is an object with:

Field Value
level The number of stars.
keyword, done The TODO keyword or null, and whether it is a done keyword.
priority The cookie's value ("A") or null.
title The title as written, without keyword, priority or tags.
tags The heading's own tags, without inherited ones.
start, end Where the heading line starts and where its subtree ends (the start of the next heading at its level or above, or the end of the file).
titleStart, titleEnd Where the title is.
scheduled, deadline, closed The planning line's timestamps as written ("<2026-11-30 Mon>"), or null.
properties The property drawer as an object ({EFFORT: "1:00"}).

org.prompt takes message, initial (text the answer starts with), choices (answers to complete from), requireMatch (the answer must be one of choices; default false) and date (ask for a date as Org's date prompt does, and give YYYY-MM-DD or YYYY-MM-DD HH:MM). org.prompt("Week: ") is short for org.prompt({message: "Week: "}).

The return value

The function returns an object with any of these, or nothing:

Field Value
edits A list of {from, to, text} in the text the command was given, or after org.run, in the text the last org.run gave. to defaults to from (an insertion) and text to "" (a deletion). Edits may not overlap or start at the same offset.
selection Where the caret or selection goes, in the text after the edits: an offset, {from, to}, or a list of them. Without it, the selection moves with the edits.
message Text for the echo area.
copy Text for the clipboard (the kill ring).

orgstar checks the edits before it makes any of them. An edit outside the text, edits that overlap, an edit that splits an emoji or other character in two, or an unknown field fail the command with a message such as Add Weekly Review: edits overlap, and nothing changes.

The edits are applied together as one step of undo, with the changes of the commands run with org.run, and only if the buffer is as it was when the command started. If you type, or the file changes on disk, while the command runs or waits for a prompt, its result is refused with "The file changed; try again."

Running Org's commands

org.run(id) runs a built-in command on the text as it is at that point in the command, with the caret where the command has left it, and resolves with {text, selection} after it: text is the new text and selection the selections as org.selection() gives them. The ids are those of the palette and keymap.toml (see Keys): org.todo.cycle, org.schedule, org.heading.insert and the rest. Later calls read the new text, and later org.run calls work on it.

export async function startTask(org) {
  await org.run("org.todo.cycle")        // TODO
  await org.run("org.schedule")          // asks for the date
  const { selection } = await org.run("org.heading.insert-todo")
  return { edits: [{ from: selection[0].from, text: "Follow up" }] }
}
  • One step of undo. Nothing reaches the buffer until the command returns. Then the changes of every org.run, and the command's own edits after them, apply together as one step of undo. If the command fails or is cancelled, none of them apply.
  • Prompts. A command that asks (org.schedule for a date, org.tags.set for tags) asks through the same prompt as org.prompt. Cancelling it makes org.run throw Quit.
  • Failures. A command that can't run at the caret makes org.run throw an error with the command's own message (error.message), as user-error does in Emacs. Catch it to go on; uncaught, the command ends with that message and nothing changes.
  • Messages and the clipboard. Messages and text for the clipboard from the commands run are shown and copied when the command's changes apply. Folding, sparse trees and snippet fields from them are not.
  • What it refuses. org.run throws for:

    • commands of the app (app.*: export, refile, capture, the clock, windows), except app.save, which saves the file after the command's changes apply. They need windows, other files or the network, which a command doesn't reach;
    • other user commands (user.*);
    • the editor's own commands, which aren't Org's: folding (org.cycle), movement and editing keys (edit.*), snippets and keyboard macros;
    • work Org does outside the text: running a code block (org.babel.execute, or C-c C-c on one), table formulas that need Emacs, following a link, tangling, editing a block apart, column view and the agenda. org.run throws with "id needs work outside the text here …" instead of starting it, since its result would come back after the command had ended.

Reading your folders and capturing

A command with workspace = true in commands.toml can also read the files in your folders and capture to them. Without it, these calls throw "org.search needs workspace = true on the command in commands.toml." Allowing such a command asks a separate question (see Trust). Capture is the only way a command writes to a file other than its own.

Call Gives
org.search(query) The best 50 matches of the sidebar's search: headings whose title or text have every word of query as the start of a word, and files whose text before the first heading does. Unsaved changes in open files are searched.
org.outlineOf(path) The headings of an org file (.org or .org_archive) in your folders, in order, as org.outline() describes them; offsets are in that file's text. path is relative to one of your folders (the first that has it) or absolute inside one. An open file is read as its buffer has it.
org.agenda({from, to}) The agenda's entries from from to to, both YYYY-MM-DD and both included; from defaults to today and to to from. At most 366 days and 200 entries.
org.capture(key, text, fields) Files text with the template keyed key in capture.toml and gives {template, file}, file relative to its folder.

A search match is an object with:

Field Value
file The file, relative to its folder (notes/plan.org).
title The heading's title, or for a match before the first heading the file's #+TITLE or name.
outline The titles of the headings above it, top first; [] for a top-level heading or the file.
start Where the heading starts in its file, as org.heading()'s start; 0 for the file.
heading false for a match in the text before the file's first heading.
snippet The text around the match, or null.

Agenda entries have the shape of those the x-callback-url agenda action returns (see agenda): title, todo, priority, tags, category, file, status, date, time, end and kind, those without a value left out, in the agenda's order with each day's overdue entries first. The agenda uses your agenda settings and files; calendar events and reminders are left out.

org.capture files without the capture window, by the rules of the x-callback-url capture action (see capture): fields answers the template's prompts by their text ({What: "Milk", Tags: "shop"} for %^{What} and %^g), and every prompt must have an answer, or nothing is filed and the call throws naming the missing ones. %^C and %^L insert nothing and %c is empty, since commands don't read the clipboard. Templates that make a Denote note or ask for a date tree's day are refused, and so is a template whose target is the file the command runs in: return edits for that. The entry is filed when the call returns, even if the command fails later, as a change of the target file alone; the undo history of the command's own file is unchanged.

// commands.toml: workspace = true
export async function followUp(org) {
  const here = await org.heading()
  if (!here) return org.fail("Not in an entry")
  const elsewhere = (await org.search(here.title)).filter(m => m.start !== here.start)
  const see = elsewhere.length ? ` (see ${elsewhere[0].file})` : ""
  await org.capture("t", `Follow up: ${here.title}${see}`)
  const today = await org.agenda()
  return { message: `Captured; ${today.length} entries on today's agenda` }
}

Text that is encrypted on disk is never returned. org.search leaves out .gpg files, searches open files with entries decrypted as they are on disk, and gives null as the snippet of a match in an encrypted entry. org.outlineOf refuses .gpg files and reads a file with entries decrypted from disk. The agenda reads such files from disk, as it always does.

Examples

commands/headings.js upcases the current heading's title:

export async function upcaseTitle(org) {
  const heading = await org.heading()
  if (!heading) return org.fail("Not in an entry")
  const text = await org.text()
  const title = text.slice(heading.titleStart, heading.titleEnd)
  return {
    edits: [{ from: heading.titleStart, to: heading.titleEnd, text: title.toUpperCase() }],
    message: `Upcased ${title}`,
  }
}

commands/review.js asks for a week and adds a child heading at the end of the current entry's subtree, with the caret after its stars:

export async function weeklyReview(org) {
  const heading = await org.heading()
  if (!heading) return org.fail("Not on a heading")
  const week = await org.prompt({ message: "Week: ", initial: "W48" })
  const stars = "*".repeat(heading.level + 1)
  return {
    edits: [{ from: heading.end, to: heading.end, text: `${stars} Review ${week}\n` }],
    selection: heading.end + stars.length + 1,
  }
}

commands/outline.js copies the path of the current entry, using the outline:

export async function copyPath(org) {
  const here = await org.heading()
  if (!here) return org.fail("Not in an entry")
  const outline = await org.outline()
  const path = outline.filter(h => h.start <= here.start && h.end >= here.end).map(h => h.title).join(" / ")
  return { copy: path, message: `Copied ${path}` }
}

Bind a command like any other in keymap.toml:

[[bind]]
keys = "C-c u"
command = "user.upcase-title"

Running a command

Run a command from the palette, a key bound in keymap.toml, the Commands list on iPhone and iPad, or a key bar button ([key-bar] in config.toml takes user. ids). The echo area shows "Running /title/… (⌘. to cancel)" while it runs.

Trust

The first time you run a command from a file, orgstar asks:

Run commands from commands/review.js?
It imports commands/lib/dates.js.
They can read and change the file you run them in, and nothing else: no other files and no network.

For a command with workspace = true, the last line is "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network."

The question names the file's full path under commands/ and every module it imports, directly or through another module; the line about imports is left out when there are none. On the Mac the question is in the echo area, with the answers listed above it; on iPhone and iPad it is an alert. Limits has the details of what a command can't reach. The answers are Run Once, Always and Don't Run:

  • Run Once runs it this time and asks again next time.
  • Always runs it and doesn't ask again while the file and every module it imports stay as they are.
  • Don't Run, or cancelling, runs nothing.

Trust for workspace = true is kept apart from trust for the buffer alone. A file you allowed with Always for commands without it asks again the first time one of its commands has workspace = true, including when you add workspace = true to a command you have run before. Always for a command with it also covers the file's other commands.

Any change to the file or to a module it imports asks again, including a change that arrives by sync from another device. Trust is kept on each device, in trusted.json in orgstar's data folder, not in the configuration folder, so a command synced from another device runs here only after you allow it here. Code blocks and Lisp table formulas use the same store (see Code blocks).

Cancelling

Edit ▸ Cancel Running Task (⌘., app.babel.cancel) stops a running command; the Commands list on iPhone and iPad has the same command. Nothing it returned is applied. Running another user command cancels the one before it.

Limits

  • Time. A command that runs longer than its timeout (2 seconds by default, at most 30) is stopped with "title didn't finish within n s and was stopped." Time waiting for a prompt doesn't count.
  • Memory. A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
  • The buffer only. A command reads and changes the buffer it runs in, nothing else: no files, no network (fetch, XMLHttpRequest, WebSocket, importScripts and the rest are removed), no other buffers, no clipboard reads, no notifications, Calendar or other system services. With workspace = true it can also read your folders through the calls in Reading your folders and capturing and capture to them, and nothing more: no files outside your folders (a symlink that leads out of them is refused) and still no network.
  • Encrypted text. Commands don't run in an encrypted file or in a buffer with entries decrypted that are encrypted on disk: "file has decrypted entries, so user commands don't run in it." The calls that read your folders never return text that is encrypted on disk.
  • Time in calls. Time the app spends answering a call (a prompt, a search, reading the agenda) doesn't count against the timeout.
  • Keyboard macros record a key bound to a user command with the answers to its prompts, and wait for the command to finish when they play (see Keyboard macros).
  • Startup. When you have commands, the engine that runs them starts when an editor opens, so the first run doesn't wait for it. It stops after five minutes without a run.

Compared with Emacs Lisp

User commands cover the small interactive commands people keep in init.el: insert a dated heading, set a property from a prompt, toggle a tag, clean up a list, convert the region. They are written in JavaScript rather than Emacs Lisp, and the API is orgstar's, not Emacs's. Import from Emacs lists bindings to functions your configuration defines with defun as not imported, with a note pointing here.

What Emacs Lisp has that user commands don't:

  • Emacs Lisp functions and packages (dash, s, org-ql); .el files aren't read.
  • Buffer primitives: point, goto-char, insert, re-search-forward on the buffer, save-excursion, markers. A command gets the text and returns edits instead.
  • The Org API: org-element-*, org-entry-put. Read headings with org.heading() and org.outline(), and write the text yourself or run Org's commands with org.run. Over several files, a command with workspace = true reads with org.search and org.outlineOf and writes only with org.capture.
  • Other buffers, find-file and with-temp-buffer; changes to other files except by capture.
  • Hooks (org-after-todo-state-change-hook, post-command-hook), advice, minor modes and buffer-local variables.
  • interactive codes other than the prompts above; C-u prefix arguments.
  • Timers, processes and shell commands.

Porting table

Emacs Lisp User command
(buffer-string) await org.text()
(point), (region-beginning), (region-end) (await org.selection())[0]
(org-get-heading t t t t) (await org.heading()).title
(org-get-todo-state) (await org.heading()).keyword
(org-get-tags nil t) (await org.heading()).tags
(org-entry-get nil "EFFORT") (await org.heading()).properties.EFFORT
(org-entry-get nil "SCHEDULED") (await org.heading()).scheduled
(org-map-entries …) in the current file (await org.outline()).forEach(…)
(org-end-of-subtree) (await org.heading()).end
(buffer-file-name) await org.file()
org-todo-keywords, org-tag-alist (await org.settings()).todoKeywords, .tags
(read-string "Week: " "W48") await org.prompt({message: "Week: ", initial: "W48"})
(completing-read "Tag: " tags nil t) await org.prompt({message: "Tag: ", choices: tags, requireMatch: true})
(org-read-date) await org.prompt({message: "Date: ", date: true})
(insert …), (delete-region …), (replace-match …) An entry in edits
(goto-char …), (set-mark …) selection
(message …) org.message(…) or message
(user-error …) return org.fail(…)
(kill-new …) copy
(org-todo) await org.run("org.todo.cycle")
(org-schedule nil), (org-deadline nil) await org.run("org.schedule"), org.run("org.deadline")
(org-insert-heading), (org-insert-todo-heading nil) await org.run("org.heading.insert"), org.run("org.heading.insert-todo")
(org-set-tags-command) await org.run("org.tags.set")
(org-set-effort), (org-set-property …) await org.run("org.effort.set"), org.run("org.property.read-and-set")
(org-promote-subtree), (org-demote-subtree) await org.run("org.subtree.promote"), org.run("org.subtree.demote")
(org-toggle-checkbox) await org.run("org.checkbox.toggle")
(save-buffer) await org.run("app.save")
(org-ql-select (org-agenda-files) '(regexp "milk")) await org.search("milk") (workspace = true)
(org-map-entries … nil 'agenda) over files await org.outlineOf(file) for each file (workspace = true)
(org-agenda-get-day-entries file date), (org-agenda-list) await org.agenda({from, to}) (workspace = true)
(org-capture-string "Milk" "t"), (org-capture nil "t") await org.capture("t", "Milk", {…}) (workspace = true)
(global-set-key (kbd "C-c u") #'my/command) [[bind]] in keymap.toml with command = "user.…"
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form