docs/manual/guide/18-user-commands.org
424 lines · 38561 bytes
1#+TITLE: User commands
2#+DESCRIPTION: Your own editing commands in JavaScript: commands.toml, the commands folder, the org API, hooks, 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
33workspace = false # optional; true lets it read your folders and capture
34
35[[command]]
36name = "weekly-review"
37title = "Add Weekly Review"
38file = "review.js"
39function = "weeklyReview"
40#+END_SRC
41
42| Key | Required | What it sets |
43|------------+----------+-----------------------------------------------------------------------------------------------------------------------------------------|
44| =api= | Yes | The API version the commands are written for, at the top of the file. This version of orgstar runs =1=. |
45| =name= | Yes | Letters, digits, =-= and =_=. The command's id is =user.=/name/. |
46| =title= | No | The title in the palette, the Commands list and key hints, shown as written. |
47| =file= | Yes | A =.js= or =.mjs= file in =commands/=, which may be in a subfolder (=lib/dates.js=). |
48| =function= | Yes | The name of a function the file exports. It may be =async=. |
49| =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. |
50| =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. |
51| =workspace= | No | =true= lets the command search your folders, read other files' outlines and the agenda, and capture (see [[*Reading your folders and capturing][Reading your folders and capturing]]). Default =false=. |
52
53orgstar 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.
54
55Problems 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:
56
57- =commands.toml: command weekly-review: no file commands/review.js=
58- =commands.toml: command slow: timeout must be 1 to 30 seconds=
59- =commands.toml: command review: unknown context headline=
60- =commands.toml: command find: workspace must be true or false=
61- =commands.toml: hook at line 12: unknown event post-command; the events are after-todo-state-change and capture-before-finalize= (see [[*Hooks][Hooks]])
62- =commands.toml: api 2 needs a newer orgstar= (no command is registered)
63- =commands.toml: missing api = 1= (no command is registered)
64- =commands.toml: commands/review.js isn't downloaded from iCloud yet= (iPhone and iPad; the download starts)
65
66* The commands folder
67
68Files 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.
69
70The function is called with one argument, =org=, the API below. Its return value says what to change.
71
72* The API, version 1
73
74Every 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.
75
76| Call | Gives |
77|----------------------------+-----------------------------------------------------------------------------------------------------------------------------|
78| =org.text()= | The buffer's text: as the command started, or as the last =org.run= left it. |
79| =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. |
80| =org.heading(at)= | The heading whose entry holds the offset =at= (default: the caret), as described below, or =null= before the first heading. |
81| =org.outline()= | Every heading in the file, in order, as =org.heading()= describes it. |
82| =org.file()= | The file's path relative to its folder (=notes/plan.org=), or =null= for a buffer without a file. |
83| =org.settings()= | =todoKeywords=, =doneKeywords=, =priorities= (={highest, lowest, default}=), =fileTags=, =tags= (the tags used in your folders), =fillColumn= and =tagsColumn=. |
84| =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. |
85| =org.message(text)= | Shows =text= in the echo area while the command runs. |
86| =org.fail(text)= | Ends the command: nothing changes and =text= is shown. Use it as =return org.fail("…")=. |
87| =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]]. |
88| =org.search(query)= | With =workspace = true=: headings and files in your folders that match =query=. See [[*Reading your folders and capturing][Reading your folders and capturing]]. |
89| =org.outlineOf(path)= | With =workspace = true=: the headings of another org file in your folders, as =org.outline()= gives them. |
90| =org.agenda({from, to})= | With =workspace = true=: the agenda's entries for a span of days. |
91| =org.capture(key, text, fields)= | With =workspace = true=: files =text= with a capture template. |
92| =org.version= | =1=. |
93
94A heading is an object with:
95
96| Field | Value |
97|--------------------------+---------------------------------------------------------------------------------------------------------|
98| =level= | The number of stars. |
99| =keyword=, =done= | The TODO keyword or =null=, and whether it is a done keyword. |
100| =priority= | The cookie's value (="A"=) or =null=. |
101| =title= | The title as written, without keyword, priority or tags. |
102| =tags= | The heading's own tags, without inherited ones. |
103| =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). |
104| =titleStart=, =titleEnd= | Where the title is. |
105| =scheduled=, =deadline=, =closed= | The planning line's timestamps as written (="<2026-11-30 Mon>"=), or =null=. |
106| =properties= | The property drawer as an object (={EFFORT: "1:00"}=). |
107
108=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: "})=.
109
110** The return value
111
112The function returns an object with any of these, or nothing:
113
114| Field | Value |
115|-------------+---------------------------------------------------------------------------------------------------------------------------------------------|
116| =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. |
117| =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. |
118| =message= | Text for the echo area. |
119| =copy= | Text for the clipboard (the kill ring). |
120
121orgstar 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.
122
123The 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."
124
125** Running Org's commands
126
127=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.
128
129#+BEGIN_SRC js
130export async function startTask(org) {
131 await org.run("org.todo.cycle") // TODO
132 await org.run("org.schedule") // asks for the date
133 const { selection } = await org.run("org.heading.insert-todo")
134 return { edits: [{ from: selection[0].from, text: "Follow up" }] }
135}
136#+END_SRC
137
138- *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.
139- *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=.
140- *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.
141- *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.
142- *What it refuses.* =org.run= throws for:
143 - 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;
144 - other user commands (=user.*=);
145 - the editor's own commands, which aren't Org's: folding (=org.cycle=), movement and editing keys (=edit.*=), snippets and keyboard macros;
146 - 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.
147
148** Reading your folders and capturing
149
150A 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][Trust]]). Capture is the only way a command writes to a file other than its own.
151
152| Call | Gives |
153|-----------------------------------+------------------------------------------------------------------------------------------------------------------|
154| =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. |
155| =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. |
156| =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. |
157| =org.capture(key, text, fields)= | Files =text= with the template keyed =key= in =capture.toml= and gives ={template, file}=, =file= relative to its folder. |
158
159A search match is an object with:
160
161| Field | Value |
162|-----------+---------------------------------------------------------------------------------------------------------|
163| =file= | The file, relative to its folder (=notes/plan.org=). |
164| =title= | The heading's title, or for a match before the first heading the file's =#+TITLE= or name. |
165| =outline= | The titles of the headings above it, top first; =[]= for a top-level heading or the file. |
166| =start= | Where the heading starts in its file, as =org.heading()='s =start=; =0= for the file. |
167| =heading= | =false= for a match in the text before the file's first heading. |
168| =snippet= | The text around the match, or =null=. |
169
170Agenda entries have the shape of those the x-callback-url =agenda= action returns (see [[file:15-alongside-emacs.org::*agenda][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.
171
172=org.capture= files without the capture window, by the rules of the x-callback-url =capture= action (see [[file:15-alongside-emacs.org::*capture][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.
173
174#+BEGIN_SRC js
175// commands.toml: workspace = true
176export async function followUp(org) {
177 const here = await org.heading()
178 if (!here) return org.fail("Not in an entry")
179 const elsewhere = (await org.search(here.title)).filter(m => m.start !== here.start)
180 const see = elsewhere.length ? ` (see ${elsewhere[0].file})` : ""
181 await org.capture("t", `Follow up: ${here.title}${see}`)
182 const today = await org.agenda()
183 return { message: `Captured; ${today.length} entries on today's agenda` }
184}
185#+END_SRC
186
187Text 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.
188
189* Examples
190
191=commands/headings.js= upcases the current heading's title:
192
193#+BEGIN_SRC js
194export async function upcaseTitle(org) {
195 const heading = await org.heading()
196 if (!heading) return org.fail("Not in an entry")
197 const text = await org.text()
198 const title = text.slice(heading.titleStart, heading.titleEnd)
199 return {
200 edits: [{ from: heading.titleStart, to: heading.titleEnd, text: title.toUpperCase() }],
201 message: `Upcased ${title}`,
202 }
203}
204#+END_SRC
205
206=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:
207
208#+BEGIN_SRC js
209export async function weeklyReview(org) {
210 const heading = await org.heading()
211 if (!heading) return org.fail("Not on a heading")
212 const week = await org.prompt({ message: "Week: ", initial: "W48" })
213 const stars = "*".repeat(heading.level + 1)
214 return {
215 edits: [{ from: heading.end, to: heading.end, text: `${stars} Review ${week}\n` }],
216 selection: heading.end + stars.length + 1,
217 }
218}
219#+END_SRC
220
221=commands/outline.js= copies the path of the current entry, using the outline:
222
223#+BEGIN_SRC js
224export async function copyPath(org) {
225 const here = await org.heading()
226 if (!here) return org.fail("Not in an entry")
227 const outline = await org.outline()
228 const path = outline.filter(h => h.start <= here.start && h.end >= here.end).map(h => h.title).join(" / ")
229 return { copy: path, message: `Copied ${path}` }
230}
231#+END_SRC
232
233Bind a command like any other in =keymap.toml=:
234
235#+BEGIN_SRC toml
236[[bind]]
237keys = "C-c u"
238command = "user.upcase-title"
239#+END_SRC
240
241* Running a command
242
243Run 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.
244
245** Trust
246
247The first time you run a command from a file, orgstar asks:
248
249#+BEGIN_EXAMPLE
250Run commands from commands/review.js?
251It imports commands/lib/dates.js.
252They can read and change the file you run them in, and nothing else: no other files and no network.
253#+END_EXAMPLE
254
255For 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."
256
257The 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:
258
259- Run Once runs it this time and asks again next time.
260- Always runs it and doesn't ask again while the file and every module it imports stay as they are.
261- Don't Run, or cancelling, runs nothing.
262
263Trust 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.
264
265Any 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]]).
266
267** Cancelling
268
269Edit ▸ 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.
270
271* Hooks
272
273A hook is a function that runs when something happens rather than from a key: after you change an entry's TODO state, or before a capture is filed. Declare it in =commands.toml= as =[[hook]]=, beside the commands:
274
275#+BEGIN_SRC toml
276api = 1
277
278[[hook]]
279event = "after-todo-state-change" # org-after-todo-state-change-hook
280file = "todo.js"
281function = "logState"
282timeout = 2 # optional, as for commands
283workspace = false # optional, as for commands
284
285[[hook]]
286event = "capture-before-finalize" # org-capture-before-finalize-hook
287file = "capture.js"
288function = "check"
289#+END_SRC
290
291| Key | Required | What it sets |
292|-------------+----------+-------------------------------------------------------------------------------------------------|
293| =event= | Yes | =after-todo-state-change= or =capture-before-finalize=. |
294| =file= | Yes | As for a command. |
295| =function= | Yes | As for a command. |
296| =timeout= | No | As for a command: 1 to 30 seconds, 2 when not given. |
297| =workspace= | No | As for a command: =true= gives the hook the calls of [[*Reading your folders and capturing][Reading your folders and capturing]]. |
298
299An event may have several hooks; they run one after another, in the order of the file, as the functions of an Emacs hook do. Problems are reported by line, as =commands.toml: hook at line 12: no file commands/todo.js=, and the hook with the problem isn't used.
300
301The function is called with =org= and a second argument that describes the event. It returns =edits= and =message= as a command does, or nothing; =selection= and =copy= fail the hook with "/function/ in /file/: a hook returns only edits and message". =org.prompt= throws in a hook, and so does =org.run= with a command that asks: a hook can run where nobody can answer.
302
303There are no hooks that run on every key or every change (=post-command-hook=, =after-change-functions=, =post-self-insert-hook=): a hook runs in the same engine as a command, which takes too long for that.
304
305** after-todo-state-change
306
307Runs after a change of an entry's TODO keyword has been made: by the TODO commands in the editor (=C-c C-t=, =S-right=, =S-left=, the TODO keyword picker), =C-c C-c= on a heading, setting the =TODO= property, and clocking in with =org-clock-in-switch-to-state=; and in the agenda, the board, column view, the entry sheet on iPhone and iPad and the Apple Watch's Done. The second argument is:
308
309| Field | Value |
310|---------+----------------------------------------------------------------------------------------------------------|
311| =entry= | The entry after the change, as =org.heading()= describes it. |
312| =from= | The keyword before, or =null=. |
313| =to= | The keyword set, or =null=. For a repeating entry marked done it is the done keyword, though the repeat has put the entry back to =TODO=, as =org-state= is in Org's hook. |
314
315The hook runs on the file as the change left it: =org.text()=, =org.heading()= and =org.outline()= read that text, and the caret is at the start of the entry's heading. Its edits apply as a step of undo of their own, after the change's, so undoing once takes back the hook's edits and leaves the change. In a file that isn't open (a change from the agenda), the file is written at once. If the file changes before the hook's edits apply, as when you type while it runs, they aren't made: "/file/ changed while /function/ in /file/ ran; its changes weren't made."
316
317The change itself stays whatever the hook does. A hook that fails, throws or runs out of time shows why, and the next hook runs.
318
319Changes a hook or a user command makes don't run hooks: a hook that runs =org.run("org.todo.cycle")= doesn't run itself again. Nor do the command-line tool, Replace in Files and renaming a keyword in every file. Encrypted files and buffers with decrypted entries run no hooks, as they run no commands.
320
321#+BEGIN_SRC js
322// commands/todo.js: a line under the heading when an entry is done.
323export async function logState(org, { entry, from, to }) {
324 if (to !== "DONE") return
325 const text = await org.text()
326 const lineEnd = text.indexOf("\n", entry.start) + 1
327 return {
328 edits: [{ from: lineEnd, text: `- Done; was ${from ?? "no keyword"}\n` }],
329 message: `Done: ${entry.title}`,
330 }
331}
332#+END_SRC
333
334** capture-before-finalize
335
336Runs when you file a capture, before the entry is placed: from the capture window on the Mac, the capture sheet on iPhone and iPad, an x-callback-url =capture= without the sheet, and Shortcuts' Capture to Orgstar. The second argument is ={text, template}=: the entry as the template filled it and you edited it, and the template's key.
337
338The hook works on the capture as Emacs's does in the capture buffer: =org.text()= is the capture's text, =org.heading()= and =org.outline()= read its headings, =org.file()= gives =null=, and its =edits= change it. The entry is filed with the changed text. =org.fail(text)=, an error or the timeout cancels the capture: nothing is filed and the reason is shown, in the window or sheet, which stays open, or in the reply to the x-callback-url or the Shortcuts action.
339
340#+BEGIN_SRC js
341// commands/capture.js: tag entries about bills, and refuse an empty title.
342export async function check(org, { text, template }) {
343 const heading = await org.heading(0)
344 if (heading && !heading.title.trim()) return org.fail("The entry needs a title")
345 if (template !== "t" || !/\bbill\b/i.test(text)) return
346 const lineEnd = text.indexOf("\n")
347 return { edits: [{ from: lineEnd < 0 ? text.length : lineEnd, text: " :money:" }] }
348}
349#+END_SRC
350
351Capture hooks don't run for =org.capture= in a user command or a hook, for org-roam and dailies captures made without the capture window, or for =orgstar capture= (see [[file:17-command-line.org::*capture][capture]]), which files without them and says so.
352
353** Trust for hooks
354
355A hook's file is trusted as a command's is (see [[*Trust][Trust]]), and the same trust covers both: Always for one of the file's commands also lets its hooks run, and the other way round. The first time a hook from a file not trusted on this device would run, orgstar asks "Run hooks from commands/todo.js?", with a line saying when the hook runs. The question is an alert on the Mac, since hooks run from the agenda and the capture window too, and on iPhone and iPad.
356
357Where orgstar can't ask (an x-callback-url capture without the sheet, Shortcuts), a hook from a file not trusted here is skipped and the capture is filed without it, with "/function/ in /file/: commands/capture.js isn't trusted on this device yet, and orgstar can't ask here." Don't Run skips the hook this time, with "Not run".
358
359* Limits
360
361- *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.
362- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
363- *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][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.
364- *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.
365- *Time in calls.* Time the app spends answering a call (a prompt, a search, reading the agenda) doesn't count against the =timeout=.
366- *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]]).
367- *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.
368
369* Compared with Emacs Lisp
370
371User 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.
372
373What Emacs Lisp has that user commands don't:
374
375- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read.
376- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
377- 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=.
378- Other buffers, =find-file= and =with-temp-buffer=; changes to other files except by capture.
379- Hooks other than =org-after-todo-state-change-hook= and =org-capture-before-finalize-hook= (see [[*Hooks][Hooks]]): no =post-command-hook=, =after-change-functions= or other per-keystroke hooks. Advice, minor modes and buffer-local variables.
380- =interactive= codes other than the prompts above; =C-u= prefix arguments.
381- Timers, processes and shell commands.
382
383** Porting table
384
385| Emacs Lisp | User command |
386|----------------------------------------------------+--------------------------------------------------------------------|
387| =(buffer-string)= | =await org.text()= |
388| =(point)=, =(region-beginning)=, =(region-end)= | =(await org.selection())[0]= |
389| =(org-get-heading t t t t)= | =(await org.heading()).title= |
390| =(org-get-todo-state)= | =(await org.heading()).keyword= |
391| =(org-get-tags nil t)= | =(await org.heading()).tags= |
392| =(org-entry-get nil "EFFORT")= | =(await org.heading()).properties.EFFORT= |
393| =(org-entry-get nil "SCHEDULED")= | =(await org.heading()).scheduled= |
394| =(org-map-entries …)= in the current file | =(await org.outline()).forEach(…)= |
395| =(org-end-of-subtree)= | =(await org.heading()).end= |
396| =(buffer-file-name)= | =await org.file()= |
397| =org-todo-keywords=, =org-tag-alist= | =(await org.settings()).todoKeywords=, =.tags= |
398| =(read-string "Week: " "W48")= | =await org.prompt({message: "Week: ", initial: "W48"})= |
399| =(completing-read "Tag: " tags nil t)= | =await org.prompt({message: "Tag: ", choices: tags, requireMatch: true})= |
400| =(org-read-date)= | =await org.prompt({message: "Date: ", date: true})= |
401| =(insert …)=, =(delete-region …)=, =(replace-match …)= | An entry in =edits= |
402| =(goto-char …)=, =(set-mark …)= | =selection= |
403| =(message …)= | =org.message(…)= or =message= |
404| =(user-error …)= | =return org.fail(…)= |
405| =(kill-new …)= | =copy= |
406| =(org-todo)= | =await org.run("org.todo.cycle")= |
407| =(org-schedule nil)=, =(org-deadline nil)= | =await org.run("org.schedule")=, =org.run("org.deadline")= |
408| =(org-insert-heading)=, =(org-insert-todo-heading nil)= | =await org.run("org.heading.insert")=, =org.run("org.heading.insert-todo")= |
409| =(org-set-tags-command)= | =await org.run("org.tags.set")= |
410| =(org-set-effort)=, =(org-set-property …)= | =await org.run("org.effort.set")=, =org.run("org.property.read-and-set")= |
411| =(org-promote-subtree)=, =(org-demote-subtree)= | =await org.run("org.subtree.promote")=, =org.run("org.subtree.demote")= |
412| =(org-toggle-checkbox)= | =await org.run("org.checkbox.toggle")= |
413| =(save-buffer)= | =await org.run("app.save")= |
414| =(org-ql-select (org-agenda-files) '(regexp "milk"))= | =await org.search("milk")= (=workspace = true=) |
415| =(org-map-entries … nil 'agenda)= over files | =await org.outlineOf(file)= for each file (=workspace = true=) |
416| =(org-agenda-get-day-entries file date)=, =(org-agenda-list)= | =await org.agenda({from, to})= (=workspace = true=) |
417| =(org-capture-string "Milk" "t")=, =(org-capture nil "t")= | =await org.capture("t", "Milk", {…})= (=workspace = true=) |
418| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |
419| =(add-hook 'org-after-todo-state-change-hook #'my/fn)= | =[[hook]]= with =event = "after-todo-state-change"= |
420| =org-state=, =org-last-state= in that hook | =to= and =from= of the hook's second argument |
421| =(add-hook 'org-capture-before-finalize-hook #'my/fn)= | =[[hook]]= with =event = "capture-before-finalize"= |
422| =(buffer-string)= in the capture buffer | =await org.text()=, or =text= of the hook's second argument |
423| =(plist-get org-capture-plist :key)= | =template= of the hook's second argument |
424| =(user-error …)= in a capture hook | =return org.fail(…)=: the capture is canceled |