docs/manual/guide/18-user-commands.org
238 lines · 18431 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 when the command started. |
75| =org.selection()= | The selections as =[{from, to}]=, the main caret first. With nothing selected, =from= and =to= are both the caret. |
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.version= | =1=. |
84
85A heading is an object with:
86
87| Field | Value |
88|--------------------------+---------------------------------------------------------------------------------------------------------|
89| =level= | The number of stars. |
90| =keyword=, =done= | The TODO keyword or =null=, and whether it is a done keyword. |
91| =priority= | The cookie's value (="A"=) or =null=. |
92| =title= | The title as written, without keyword, priority or tags. |
93| =tags= | The heading's own tags, without inherited ones. |
94| =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). |
95| =titleStart=, =titleEnd= | Where the title is. |
96| =scheduled=, =deadline=, =closed= | The planning line's timestamps as written (="<2026-11-30 Mon>"=), or =null=. |
97| =properties= | The property drawer as an object (={EFFORT: "1:00"}=). |
98
99=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: "})=.
100
101** The return value
102
103The function returns an object with any of these, or nothing:
104
105| Field | Value |
106|-------------+---------------------------------------------------------------------------------------------------------------------------------------------|
107| =edits= | A list of ={from, to, text}= in the text the command was given. =to= defaults to =from= (an insertion) and =text= to =""= (a deletion). Edits may not overlap or start at the same offset. |
108| =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. |
109| =message= | Text for the echo area. |
110| =copy= | Text for the clipboard (the kill ring). |
111
112orgstar 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.
113
114The edits are applied together as one step of undo, 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."
115
116* Examples
117
118=commands/headings.js= upcases the current heading's title:
119
120#+BEGIN_SRC js
121export async function upcaseTitle(org) {
122 const heading = await org.heading()
123 if (!heading) return org.fail("Not in an entry")
124 const text = await org.text()
125 const title = text.slice(heading.titleStart, heading.titleEnd)
126 return {
127 edits: [{ from: heading.titleStart, to: heading.titleEnd, text: title.toUpperCase() }],
128 message: `Upcased ${title}`,
129 }
130}
131#+END_SRC
132
133=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:
134
135#+BEGIN_SRC js
136export async function weeklyReview(org) {
137 const heading = await org.heading()
138 if (!heading) return org.fail("Not on a heading")
139 const week = await org.prompt({ message: "Week: ", initial: "W48" })
140 const stars = "*".repeat(heading.level + 1)
141 return {
142 edits: [{ from: heading.end, to: heading.end, text: `${stars} Review ${week}\n` }],
143 selection: heading.end + stars.length + 1,
144 }
145}
146#+END_SRC
147
148=commands/outline.js= copies the path of the current entry, using the outline:
149
150#+BEGIN_SRC js
151export async function copyPath(org) {
152 const here = await org.heading()
153 if (!here) return org.fail("Not in an entry")
154 const outline = await org.outline()
155 const path = outline.filter(h => h.start <= here.start && h.end >= here.end).map(h => h.title).join(" / ")
156 return { copy: path, message: `Copied ${path}` }
157}
158#+END_SRC
159
160Bind a command like any other in =keymap.toml=:
161
162#+BEGIN_SRC toml
163[[bind]]
164keys = "C-c u"
165command = "user.upcase-title"
166#+END_SRC
167
168* Running a command
169
170Run 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.
171
172** Trust
173
174The first time you run a command from a file, orgstar asks:
175
176#+BEGIN_EXAMPLE
177Run commands from commands/review.js?
178#+END_EXAMPLE
179
180A command can read and change the file you run it in, and nothing else (see [[*Limits][Limits]]). The answers are Run Once, Always and Don't Run:
181
182- Run Once runs it this time and asks again next time.
183- Always runs it and doesn't ask again while the file and every module it imports stay as they are.
184- Don't Run, or cancelling, runs nothing.
185
186Any 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]]).
187
188** Cancelling
189
190Edit ▸ 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.
191
192* Limits
193
194- *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.
195- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
196- *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.
197- *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."
198- *Keyboard macros* don't wait for a user command to finish.
199- *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.
200
201* Compared with Emacs Lisp
202
203User 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.
204
205What Emacs Lisp has that user commands don't:
206
207- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read.
208- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
209- The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=, calling Org's own commands (=org-todo=, =org-schedule=). Read headings with =org.heading()= and =org.outline()=, and write the text yourself.
210- Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command.
211- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables.
212- =interactive= codes other than the prompts above; =C-u= prefix arguments.
213- Timers, processes and shell commands.
214
215** Porting table
216
217| Emacs Lisp | User command |
218|----------------------------------------------------+--------------------------------------------------------------------|
219| =(buffer-string)= | =await org.text()= |
220| =(point)=, =(region-beginning)=, =(region-end)= | =(await org.selection())[0]= |
221| =(org-get-heading t t t t)= | =(await org.heading()).title= |
222| =(org-get-todo-state)= | =(await org.heading()).keyword= |
223| =(org-get-tags nil t)= | =(await org.heading()).tags= |
224| =(org-entry-get nil "EFFORT")= | =(await org.heading()).properties.EFFORT= |
225| =(org-entry-get nil "SCHEDULED")= | =(await org.heading()).scheduled= |
226| =(org-map-entries …)= in the current file | =(await org.outline()).forEach(…)= |
227| =(org-end-of-subtree)= | =(await org.heading()).end= |
228| =(buffer-file-name)= | =await org.file()= |
229| =org-todo-keywords=, =org-tag-alist= | =(await org.settings()).todoKeywords=, =.tags= |
230| =(read-string "Week: " "W48")= | =await org.prompt({message: "Week: ", initial: "W48"})= |
231| =(completing-read "Tag: " tags nil t)= | =await org.prompt({message: "Tag: ", choices: tags, requireMatch: true})= |
232| =(org-read-date)= | =await org.prompt({message: "Date: ", date: true})= |
233| =(insert …)=, =(delete-region …)=, =(replace-match …)= | An entry in =edits= |
234| =(goto-char …)=, =(set-mark …)= | =selection= |
235| =(message …)= | =org.message(…)= or =message= |
236| =(user-error …)= | =return org.fail(…)= |
237| =(kill-new …)= | =copy= |
238| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |