docs/manual/guide/18-user-commands.org
272 lines · 22855 bytes
1#+TITLE: User commands
2#+DESCRIPTION: Your own editing commands in JavaScript: commands.toml, the commands folder, the org API, trust, limits, and porting commands from Emacs Lisp.
3#+LEDE: Write your own editing commands in JavaScript. They run on the Mac and on iPhone and iPad, from the palette, keys and the key bar.
4
5* Overview
6
7A 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:
8
9#+BEGIN_EXAMPLE
10~/.config/orgstar/
11 commands.toml
12 commands/
13 headings.js
14 review.js
15#+END_EXAMPLE
16
17Each 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+.
18
19The 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 [[file:14-ios.org][iPhone and iPad]]).
20
21* commands.toml
22
23#+BEGIN_SRC toml
24api = 1
25
26[[command]]
27name = "upcase-title" # the command user.upcase-title
28title = "Upcase Heading Title" # shown in the palette; default: the name
29file = "headings.js" # in commands/
30function = "upcaseTitle" # an exported function
31when = "heading" # optional; default: everywhere
32timeout = 5 # optional, seconds; default 2, at most 30
33
34[[command]]
35name = "weekly-review"
36title = "Add Weekly Review"
37file = "review.js"
38function = "weeklyReview"
39#+END_SRC
40
41| Key | Required | What it sets |
42|------------+----------+-----------------------------------------------------------------------------------------------------------------------------------------|
43| =api= | Yes | The API version the commands are written for, at the top of the file. This version of orgstar runs =1=. |
44| =name= | Yes | Letters, digits, =-= and =_=. The command's id is =user.=/name/. |
45| =title= | No | The title in the palette, the Commands list and key hints, shown as written. |
46| =file= | Yes | A =.js= or =.mjs= file in =commands/=, which may be in a subfolder (=lib/dates.js=). |
47| =function= | Yes | The name of a function the file exports. It may be =async=. |
48| =when= | No | A context from [[file:03-keys.org::*Contexts][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. |
49| =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. |
50
51orgstar 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.
52
53Problems are reported like those of the other configuration files (see [[file:13-configuration.org::*Problems in the files][Problems in the files]]), and the command with the problem isn't registered:
54
55- =commands.toml: command weekly-review: no file commands/review.js=
56- =commands.toml: command slow: timeout must be 1 to 30 seconds=
57- =commands.toml: command review: unknown context headline=
58- =commands.toml: api 2 needs a newer orgstar= (no command is registered)
59- =commands.toml: missing api = 1= (no command is registered)
60- =commands.toml: commands/review.js isn't downloaded from iCloud yet= (iPhone and iPad; the download starts)
61
62* The commands folder
63
64Files 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.
65
66The function is called with one argument, =org=, the API below. Its return value says what to change.
67
68* The API, version 1
69
70Every 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.
71
72| Call | Gives |
73|----------------------------+-----------------------------------------------------------------------------------------------------------------------------|
74| =org.text()= | The buffer's text: as the command started, or as the last =org.run= left it. |
75| =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. |
76| =org.heading(at)= | The heading whose entry holds the offset =at= (default: the caret), as described below, or =null= before the first heading. |
77| =org.outline()= | Every heading in the file, in order, as =org.heading()= describes it. |
78| =org.file()= | The file's path relative to its folder (=notes/plan.org=), or =null= for a buffer without a file. |
79| =org.settings()= | =todoKeywords=, =doneKeywords=, =priorities= (={highest, lowest, default}=), =fileTags=, =tags= (the tags used in your folders), =fillColumn= and =tagsColumn=. |
80| =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. |
81| =org.message(text)= | Shows =text= in the echo area while the command runs. |
82| =org.fail(text)= | Ends the command: nothing changes and =text= is shown. Use it as =return org.fail("…")=. |
83| =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][Running Org's commands]]. |
84| =org.version= | =1=. |
85
86A heading is an object with:
87
88| Field | Value |
89|--------------------------+---------------------------------------------------------------------------------------------------------|
90| =level= | The number of stars. |
91| =keyword=, =done= | The TODO keyword or =null=, and whether it is a done keyword. |
92| =priority= | The cookie's value (="A"=) or =null=. |
93| =title= | The title as written, without keyword, priority or tags. |
94| =tags= | The heading's own tags, without inherited ones. |
95| =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). |
96| =titleStart=, =titleEnd= | Where the title is. |
97| =scheduled=, =deadline=, =closed= | The planning line's timestamps as written (="<2026-11-30 Mon>"=), or =null=. |
98| =properties= | The property drawer as an object (={EFFORT: "1:00"}=). |
99
100=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: "})=.
101
102** The return value
103
104The function returns an object with any of these, or nothing:
105
106| Field | Value |
107|-------------+---------------------------------------------------------------------------------------------------------------------------------------------|
108| =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. |
109| =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. |
110| =message= | Text for the echo area. |
111| =copy= | Text for the clipboard (the kill ring). |
112
113orgstar 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.
114
115The 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."
116
117** Running Org's commands
118
119=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 [[file:03-keys.org][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.
120
121#+BEGIN_SRC js
122export async function startTask(org) {
123 await org.run("org.todo.cycle") // TODO
124 await org.run("org.schedule") // asks for the date
125 const { selection } = await org.run("org.heading.insert-todo")
126 return { edits: [{ from: selection[0].from, text: "Follow up" }] }
127}
128#+END_SRC
129
130- *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.
131- *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=.
132- *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.
133- *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.
134- *What it refuses.* =org.run= throws for:
135 - 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;
136 - other user commands (=user.*=);
137 - the editor's own commands, which aren't Org's: folding (=org.cycle=), movement and editing keys (=edit.*=), snippets and keyboard macros;
138 - 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.
139
140* Examples
141
142=commands/headings.js= upcases the current heading's title:
143
144#+BEGIN_SRC js
145export async function upcaseTitle(org) {
146 const heading = await org.heading()
147 if (!heading) return org.fail("Not in an entry")
148 const text = await org.text()
149 const title = text.slice(heading.titleStart, heading.titleEnd)
150 return {
151 edits: [{ from: heading.titleStart, to: heading.titleEnd, text: title.toUpperCase() }],
152 message: `Upcased ${title}`,
153 }
154}
155#+END_SRC
156
157=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:
158
159#+BEGIN_SRC js
160export async function weeklyReview(org) {
161 const heading = await org.heading()
162 if (!heading) return org.fail("Not on a heading")
163 const week = await org.prompt({ message: "Week: ", initial: "W48" })
164 const stars = "*".repeat(heading.level + 1)
165 return {
166 edits: [{ from: heading.end, to: heading.end, text: `${stars} Review ${week}\n` }],
167 selection: heading.end + stars.length + 1,
168 }
169}
170#+END_SRC
171
172=commands/outline.js= copies the path of the current entry, using the outline:
173
174#+BEGIN_SRC js
175export async function copyPath(org) {
176 const here = await org.heading()
177 if (!here) return org.fail("Not in an entry")
178 const outline = await org.outline()
179 const path = outline.filter(h => h.start <= here.start && h.end >= here.end).map(h => h.title).join(" / ")
180 return { copy: path, message: `Copied ${path}` }
181}
182#+END_SRC
183
184Bind a command like any other in =keymap.toml=:
185
186#+BEGIN_SRC toml
187[[bind]]
188keys = "C-c u"
189command = "user.upcase-title"
190#+END_SRC
191
192* Running a command
193
194Run 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.
195
196** Trust
197
198The first time you run a command from a file, orgstar asks:
199
200#+BEGIN_EXAMPLE
201Run commands from commands/review.js?
202It imports commands/lib/dates.js.
203They can read and change the file you run them in, and nothing else: no other files and no network.
204#+END_EXAMPLE
205
206The 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][Limits]] has the details of what a command can't reach. The answers are Run Once, Always and Don't Run:
207
208- Run Once runs it this time and asks again next time.
209- Always runs it and doesn't ask again while the file and every module it imports stay as they are.
210- Don't Run, or cancelling, runs nothing.
211
212Any 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 [[file:11-code-blocks.org][Code blocks]]).
213
214** Cancelling
215
216Edit ▸ 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.
217
218* Limits
219
220- *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.
221- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
222- *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.
223- *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."
224- *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 [[file:03-keys.org::*Keyboard macros][Keyboard macros]]).
225- *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.
226
227* Compared with Emacs Lisp
228
229User 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.
230
231What Emacs Lisp has that user commands don't:
232
233- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read.
234- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
235- The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=.
236- Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command.
237- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables.
238- =interactive= codes other than the prompts above; =C-u= prefix arguments.
239- Timers, processes and shell commands.
240
241** Porting table
242
243| Emacs Lisp | User command |
244|----------------------------------------------------+--------------------------------------------------------------------|
245| =(buffer-string)= | =await org.text()= |
246| =(point)=, =(region-beginning)=, =(region-end)= | =(await org.selection())[0]= |
247| =(org-get-heading t t t t)= | =(await org.heading()).title= |
248| =(org-get-todo-state)= | =(await org.heading()).keyword= |
249| =(org-get-tags nil t)= | =(await org.heading()).tags= |
250| =(org-entry-get nil "EFFORT")= | =(await org.heading()).properties.EFFORT= |
251| =(org-entry-get nil "SCHEDULED")= | =(await org.heading()).scheduled= |
252| =(org-map-entries …)= in the current file | =(await org.outline()).forEach(…)= |
253| =(org-end-of-subtree)= | =(await org.heading()).end= |
254| =(buffer-file-name)= | =await org.file()= |
255| =org-todo-keywords=, =org-tag-alist= | =(await org.settings()).todoKeywords=, =.tags= |
256| =(read-string "Week: " "W48")= | =await org.prompt({message: "Week: ", initial: "W48"})= |
257| =(completing-read "Tag: " tags nil t)= | =await org.prompt({message: "Tag: ", choices: tags, requireMatch: true})= |
258| =(org-read-date)= | =await org.prompt({message: "Date: ", date: true})= |
259| =(insert …)=, =(delete-region …)=, =(replace-match …)= | An entry in =edits= |
260| =(goto-char …)=, =(set-mark …)= | =selection= |
261| =(message …)= | =org.message(…)= or =message= |
262| =(user-error …)= | =return org.fail(…)= |
263| =(kill-new …)= | =copy= |
264| =(org-todo)= | =await org.run("org.todo.cycle")= |
265| =(org-schedule nil)=, =(org-deadline nil)= | =await org.run("org.schedule")=, =org.run("org.deadline")= |
266| =(org-insert-heading)=, =(org-insert-todo-heading nil)= | =await org.run("org.heading.insert")=, =org.run("org.heading.insert-todo")= |
267| =(org-set-tags-command)= | =await org.run("org.tags.set")= |
268| =(org-set-effort)=, =(org-set-property …)= | =await org.run("org.effort.set")=, =org.run("org.property.read-and-set")= |
269| =(org-promote-subtree)=, =(org-demote-subtree)= | =await org.run("org.subtree.promote")=, =org.run("org.subtree.demote")= |
270| =(org-toggle-checkbox)= | =await org.run("org.checkbox.toggle")= |
271| =(save-buffer)= | =await org.run("app.save")= |
272| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |