Classic API reference (API 1 to 4)
The globals API 4 plugins use: manifest, render and on_event, widgets, events, wm.*, modules and limits.
Everything an API 4 plugin can use. If it is not here, it does not exist.
Plugins are written in Python, a subset of it that matches PyMini, the small interpreter Clink uses. WM Keyboard runs it on its own Rust port of PyMini, the same one on the phone and in the web editor’s live preview. The Python you get lists what that subset has.
The manifest
Section titled “The manifest”plugin.json, at the top level of the archive.
| Field | Required | Meaning |
|---|---|---|
format | yes | Always "wmkeyboard-plugin". The one tag that identifies the file. |
version | no | Container format version. 1. |
id | yes | Unique, lowercase, 3–64 characters of a-z 0-9 . _ -, starting alphanumeric. Becomes the plugin’s folder on the device. Reverse-DNS by convention. |
name | yes | Shown everywhere. Trimmed to 40 characters, control and direction-override characters removed. |
pluginVersion | yes | Your version, e.g. "1.2.0". |
author | no | Shown on the install screen. |
description | no | One or two sentences. |
apiVersion | yes | 4. A higher number than the app knows is refused. Left out, it counts as 1, which a manifest without language cannot be; see Lua is refused. |
language | no | "python", the only language there is. Leave it out or set it; nothing else is accepted. |
entry | no | The script inside the archive. Defaults to main.py. |
permissions | no | See Permissions. Usually []. |
actions | no | Buttons on the bar over selected text. See Selection actions. Needs the selection permission. |
panel | no | false for a plugin made of actions alone: it has no render() and is left out of the keyboard’s plugin list. Defaults to true. |
Lua is refused
Section titled “Lua is refused”Plugins were written in Lua before 0.6.6. A manifest that says
"language": "lua", or that leaves language out and gives an apiVersion of
3 or lower, is a Lua plugin, and the install is refused with this reason:
written in Lua, which WM Keyboard no longer runs; look for its Python version.
A manifest that says "language": "python" with a lower apiVersion still
installs. That is how an action plugin made from a Clink action before 0.6.6
looks; a Clink action
converted today gets "apiVersion": 4. What happened to Lua plugins already on
a phone is under Lua plugins were retired.
Your functions
Section titled “Your functions”def render(): # a widget, or a list of widgets ...
def on_event(e): # optional ...
def transform(text, action): # only for selection actions ...render() is called after loading and after every event. on_event(e) is
called when the user does something. Change your variables in on_event,
describe the result in render().
All three are plain module-level functions. There is no registration step.
State lives in module globals, the variables at the top level of your script.
They keep their values for as long as the panel is open. A function that
assigns to one has to say so with global first, the way Python always asks:
count = 0
def on_event(e): global count count += 1Leave the global line out and the assignment makes a local variable instead,
with no error to tell you.
wm and ui are globals too. Neither needs an import.
Selection actions
Section titled “Selection actions”A plugin can add its own buttons to the bar that appears over selected text.
List them in the manifest, ask for the selection permission, and write
transform:
"apiVersion": 4,"permissions": ["selection"],"actions": [ { "id": "rot13", "name": "ROT13", "summary": "Shift each letter 13 places", "icon": "lock" }, { "id": "quote", "name": "Wrap in quotes" }]def transform(text, action): # a string, or None to leave the text alone if action == "rot13": return rot13(text) if action == "quote": return "“" + text + "”"A plugin with a single action can take one parameter, transform(text).
When the user selects text and taps one of your buttons, the keyboard loads
your script in a fresh interpreter, calls transform with the selected text and
the action’s id, and puts the string you return in place of the selection.
Undo on the bar takes it back. Nothing is kept between taps except what you
write to wm.storage: a global you set during one call is gone by the next.
| Action field | Meaning |
|---|---|
id | Unique within the plugin, up to 32 characters of a-z 0-9 _ -. |
name | The button’s label. Trimmed to 24 characters. |
summary | One line for the settings list. Optional. |
icon | A key icon name, the same names a layout key takes (lock, translate, link). Optional; a plugin glyph otherwise. |
replaces | false keeps the selection and adds your result after it. Defaults to true. |
input | "selection", the default, or "none" to be called with an empty string. |
Up to 16 actions. A call gets the same wm as the panel, without
wm.ui.set_input, since there is no panel for it to write into. It has the same
step and time allowance as loading your script, because every tap loads it. The
user can switch each action off in
WM Keyboard Advanced Selection actions, where actions from plugins
come after the built-in ones. They also appear in the WM Keyboard entry of
other apps’ selection menus.
A plugin can have a panel and actions at once, the way the Selection
actions template keeps the quote style its action uses. One with actions and
no panel sets "panel": false. A
Clink action installs as
exactly that: one action, no panel.
Widgets
Section titled “Widgets”Built by ui.*, which return plain dicts. You can write the dicts yourself if
you prefer: every builder below gives a dict with a type key and one key per
parameter, named as the parameter is. column and row keep their children
under children, tabs its pages under pages, and a page is
{"title": ..., "children": [...]}.
Layout
Section titled “Layout”ui.column(child, child, ...) # stacked verticallyui.row(child, child, ...) # side by side, equal widthsui.spacer(height=8) # vertical gap, 0-64ui.divider() # a horizontal linecolumn and row also take one list, which is the easy way to build children
in a loop:
ui.column([ui.label(item) for item in items])ui.label(text, style=None) # style: "title", "body" or "caption"body is the default. Labels are not interactive and have no id.
ui.output( text, id=None, mono=False, # monospace, for anything with alignment insertable=True, # show the Insert button copyable=True, # show the Copy button)ui.output is how your results reach the user’s text. The keyboard draws
Insert and Copy buttons under it. A tap on Insert puts the text where they are
writing. There is no function that types for them.
Controls
Section titled “Controls”ui.button(id, text, style=None, enabled=True)ui.toggle(id, label, checked=False)ui.input(id, label=None, placeholder=None)style="primary" highlights a button. Anything else is plain. enabled=False
grays one out.
ui.input carries no value. The keyboard owns what is in the box: a tap
points the keys at it, and you are told the contents through an input_changed
event. Use wm.ui.set_input(id, text) to write to one. This is why a plugin
never sees a keystroke. It is handed the whole contents of its own box after
each one, and nothing else.
ui.tabs("modes", ui.page("First", child, child), ui.page("Second", child),)ui.tabs(id, *pages) takes its pages after the id, and ui.page(title, *children) its children after the title. Top level only, up to 8 pages. Which
page is showing is the keyboard’s business. You get a tab_selected event if
you care.
ui.date( id, label=None, value=None, # seconds since 1970, as time.time() or wm.timestamp() give; None for no date yet time=False, # pick a time of day too step=15, # minutes the smaller time buttons move, 1-60)The keyboard draws the date between a back and a forward arrow, the time (with
time=True) between buttons that move it by step minutes and by an hour,
and Today and Clear under them. With no value it shows Set date,
which picks today, or the next whole hour when time is on.
Like ui.input, the widget keeps nothing. Each press sends a date_changed
event with the new value, and the next render draws whatever you kept. Without
time the value is the start of a day. Days move on the calendar in the phone’s
time zone, so 9:00 stays 9:00 across a clock change.
Progress
Section titled “Progress”ui.progress() # an indeterminate barEvents
Section titled “Events”on_event(e) receives a dict. It always has type and id; some events carry
more. Read them as e.type or e["type"], whichever you like.
e.type | Extra | Fired when |
|---|---|---|
"click" | none | A button was tapped. |
"toggle" | e.value (True or False) | A toggle was flipped. |
"input_changed" | e.value (a string) | The contents of one of your boxes changed. |
"tab_selected" | e.index (an int, from 0) | A tab was picked. |
"date_changed" | e.value (seconds, or None) | A date widget moved, or was cleared. |
input_changed fires per keystroke into your own input widget. That is how a
live preview works. It is bounded to your panel: you are told what is in your
box, never what is typed anywhere else.
The complete host API.
Always available
Section titled “Always available”wm.api_version # 4wm.plugin_id # your manifest idwm.plugin_version # your manifest pluginVersionwm.log(*values) # a line in your log, readable in Settingsprint writes to the same log. A line is cut at 512 characters.
wm.ui.set_input(id, text) # write to one of your own input widgetsApplied after your handler returns. Capped at 8 KB. Panel only: a selection action has no boxes to write to.
wm.timestamp(year, month, day, hour=12, minute=0, second=0)That moment in the phone’s time zone, in seconds since 1970. A field past its
range rolls over, so day=d + 1 on the last of the month is the first of the
next, and month=13 is January of the following year. This is what a date
widget and a reminder take.
With the storage permission
Section titled “With the storage permission”wm.storage.get(key, default=None) # the string, or defaultwm.storage.set(key, value) # strings onlywm.storage.remove(key)wm.storage.keys() # a list of stringsStrings only, so use json.dumps and json.loads for anything structured.
Local to your plugin, local to the device, deleted when the user uninstalls you.
set raises ValueError when you are over quota. Catch it and say something
rather than losing the data silently:
try: wm.storage.set("items", json.dumps(items))except ValueError as err: status = "Not saved: " + str(err)If the manifest did not declare storage, wm.storage is None.
With the reminders permission
Section titled “With the reminders permission”wm.reminders.set(id, seconds, text)wm.reminders.cancel(id) # True when there was onewm.reminders.list() # [{"id": ..., "time": ..., "text": ...}, ...]At seconds, a time as wm.timestamp() or time.time() gives it, the app
shows text in a notification with your plugin’s name as its title. Setting an
id that is already set replaces it. list gives every reminder not yet shown,
soonest first; a reminder leaves the list once it is shown.
Your script does not run to show it. The app keeps the id, the time and the text, and posts the notification itself, so a reminder fires with the keyboard closed. It does not fire while plugins, or your plugin, are switched off; a reminder that comes due then is dropped.
set raises ValueError for a time already past, for empty text, or past 64
reminders. Text is cut to 200 characters, with control and direction-override
characters removed.
If the manifest did not declare reminders, wm.reminders is None. A plugin
can check for that and work without it.
Not in API 4
Section titled “Not in API 4”An API 4 plugin has no network, field, clipboard or file access. Those come with API 5, behind permissions the user grants, and never include reading what the user types.
The Python you get
Section titled “The Python you get”PyMini’s subset of Python 3, grown to cover what most Python code reaches for.
The language: functions with defaults, *args, keyword-only parameters
and **kwargs, lambda, decorators, class with one base or several,
super(), @property, @staticmethod and @classmethod,
if/elif/else, for and while with break, continue and else,
try/except/finally, raise (and raise … from …), with, assert,
global, nonlocal, del, match/case (literal, capture, sequence,
mapping, class, | and as patterns, with guards), generators (yield,
yield from, and send, throw and close on the generator), the walrus
:=, ..., list, dict and set comprehensions and generator expressions, f-strings
(with {x=}, which writes x= before the value), slicing, slice assignment
(items[1:3] = new, del items[::2]), tuple unpacking with a starred target
(first, *rest = items), * and ** spreads in calls and displays, chained
comparisons, @ for classes that define __matmul__, b"…" bytes literals, type annotations (evaluated as Python evaluates them; one naming what is not defined yet is kept as its text),
import, from module import * and from __future__ import …. An exception
raised with raise … from cause keeps the cause as __cause__, and one raised
while another is being handled keeps that one as __context__; a bare raise
reports the line the exception first came from. A call with too many or too
few arguments raises the TypeError CPython would, naming every missing
argument. Names follow Python’s scoping: a variable a function assigns is local
to it everywhere in it, so reading it before the assignment raises
UnboundLocalError.
Classes work the way Python’s do for everyday code: __init__, methods,
class attributes, and the operator methods __str__, __repr__, __eq__,
__lt__ and the other comparisons, __add__ and the other arithmetic
(reflected forms too), __len__, __iter__ and __next__, __getitem__,
__setitem__, __delitem__, __contains__, __call__, __bool__,
__enter__ and __exit__, __getattr__, __setattr__, __new__,
__init_subclass__ and __class_getitem__. In-place operators ask
__iadd__ and its kin first, and builtins that want a number ask for one:
int() calls __int__, float() __float__, abs() __abs__, round()
__round__, divmod() __divmod__, bytes() __bytes__, math.floor()
__floor__, and indexing, slicing, range() and hex() call __index__.
Descriptors work as in Python: a class attribute with __get__ and __set__
or __delete__ takes over reading and writing that name on instances,
__set_name__ hears the name it was given, and __getattribute__ sees every
lookup. obj.__dict__ and vars(obj) are the instance’s own attributes,
live, so writing to them sets attributes. A class derived from Exception
or one of its kinds can be raised and caught by its own name or any base.
Several bases are put in the order Python uses (C3), and a bad mix is refused
as Python refuses it. Metaclasses work too: a class derived from type can
shape the classes made with metaclass= (its __new__ and __init__),
decide what calling them does (__call__), answer isinstance and
issubclass (__instancecheck__, __subclasscheck__), and give those classes
methods, properties, len(), for and []. Other class keywords go to
__init_subclass__.
A class can derive from dict, list, str, int, float, tuple, set
or bytes, and each instance is a value of that type: isinstance(d, dict)
holds, the type’s methods and operators work on it, and json.dumps, string
methods and wm functions take it as one. Its own methods override the
type’s, super().__setitem__(key, value) and dict.__getitem__(self, key)
reach the type’s, and a dict subclass’s __missing__ answers for a key it
lacks. A str, int or tuple subclass hashes as its value, so {Name("a"): 1}
finds "a". As in Python, what the type’s own methods hand back is the plain
type: S("a").upper() is a str, and L([1]) + [2] a list. The type
must be the only built-in base: class X(dict, list) and class B(bool) are
refused, as Python refuses them.
Async: async def, await, async for, async with and async
comprehensions work. asyncio runs them one coroutine at a time, with no
event loop: awaiting a coroutine runs it to its end, and asyncio.sleep
returns at once.
String escapes are Python’s: \n, \t, \r, \a, \b, \f, \v,
octal \101, \x41, \u00e9, \U0001F600, \N{BULLET} (a character by its
Unicode name), \\ and the quotes. An escape Python does not know, such as
\q, keeps its backslash.
Numbers: integers are exact at any size, as in Python: 2 ** 100,
math.factorial(50) and a UUID’s 128-bit .int are whole numbers, not
floats. <<, >>, &, |, ^ and ~ work on them, with their
<<=-style assignments, and int.from_bytes, n.to_bytes and
n.bit_length() read and write binary fields. An integer may grow to 2 ** 20
bits, about 315,000 digits, and past that an OverflowError says so. Turning
one into decimal text or back stops at 4,300 digits, CPython’s own limit,
which sys.set_int_max_str_digits moves. Integers compare exactly with floats
too, so 2 ** 53 + 1 > 2 ** 53, and nothing is less than, greater than or
equal to float("nan"). 1 is True is false, as
in Python. int() reads text as Python does: _ between digits, digits of
any script (int("৩") is 3), and with base 0 a 0x, 0o or 0b prefix.
Format specs take # for that prefix: f"{255:#x}" is "0xff". Dividing by
zero raises ZeroDivisionError in CPython’s words, and so does 0 ** -1.
A float prints with the fewest digits that read back as the same float, as
Python prints it: 0.1 + 0.2 is 0.30000000000000004 and 1e16 + 2 is
1.0000000000000002e+16.
Built-in functions: abs, all, any, bin, bool, callable, chr,
classmethod, delattr, dict, divmod, enumerate, filter, float,
format, getattr, hasattr, hash, hex, id, int, isinstance,
issubclass, iter, len, list, map, max, min, next, object,
oct, ord, pow, print, property, range, repr, reversed,
round, set, setattr, sorted, staticmethod, str, sum, super,
tuple, type, vars and zip, and __import__, aiter, anext,
ascii, bytearray, compile, dir, eval, exec, frozenset, globals,
locals, memoryview and slice. eval and exec run in the same sandbox, on the
same step budget, and see the scope they are called from. locals() hands
back a copy; globals() is the module’s own dict, so a name set in it is a
global from then on. compile checks that source parses and hands it to
eval or exec; there is no bytecode. open raises PermissionError and
input raises EOFError, and __import__ reaches only what import
reaches. map, filter, zip, enumerate, reversed and
range are lazy, as in Python: range(10**12) holds three numbers, not a
trillion.
They take Python’s keyword arguments: print(*values, sep=" ", end="\n"),
enumerate(items, start=1), dict(pairs, key=value),
d.update(other, key=value), sum(items, start=0), int(text, base=16),
zip(*lists, strict=True). A method also works through its type, so
sorted(names, key=str.lower) and map(str.strip, lines) do what they do in
Python, as do str.maketrans and dict.fromkeys.
Sorting and dict keys behave as in Python. sorted and list.sort are
stable, reverse=True included, and fast on long lists: ten thousand items
take a few hundred thousand steps. Numbers that are equal are one key, so
1, 1.0 and True find the same entry. An object whose class defines
__hash__ is found by value: two instances that __eq__ calls equal are one
key and one member of a set. A class with __eq__ and no __hash__ still
hashes by identity, where Python would refuse it; __hash__ = None makes it
unhashable. A frozen dataclass hashes its fields. d1 | d2 merges dicts,
|= updates a dict or set in place, and <, <=, >, >= compare sets by
inclusion. d.keys(), d.values() and d.items() are live views: they show
later changes to the dict, and keys and items combine with sets
(d.keys() & {"a", "b"}). Wrap one in list() to index it.
type(x) gives the type, as in Python: type(1) is int, type(self) is the
class, and type(x).__name__ names it. type(name, bases, attrs) makes a
class.
Strings count characters as you see them, so an emoji with a skin tone or a
letter with a combining accent is one character to len, indexing and for.
Two strings that look the same compare equal even when one spells an accent as a
separate mark. A Windows line end, "\r\n", is one character too, but
splitlines() splits there as Python does.
Dicts answer attribute reads. d.name is d["name"] when the key is
there. That is why e.type works on an event. A dict’s own methods come
first, as in Python: d.items and d.get are the methods even when the dict
has an "items" or "get" key, so read those keys with brackets. Writing
still takes brackets: d["name"] = value.
Modules: import reaches these six and nothing else.
| Module | What it has |
|---|---|
math | sqrt, isqrt, floor, ceil, trunc, fabs, pow, exp, exp2, expm1, log, log2, log10, log1p, the trigonometric and hyperbolic functions, degrees, radians, hypot, dist, gcd, lcm, factorial, comb, perm, prod, fsum, isclose, isnan, isinf, isfinite, copysign, fmod, remainder, modf, frexp, ldexp, cbrt, erf, erfc, gamma, lgamma, nextafter, ulp, fma, sumprod, and pi, e, tau, inf, nan. A value a function does not have raises CPython’s ValueError: math domain error (math.sqrt(-1)), and one too big for a float OverflowError: math range error (math.exp(1000)). |
json | dumps and loads, and dump and load on a file-like object such as io.StringIO, with CPython’s options: indent, sort_keys, separators, ensure_ascii, skipkeys, allow_nan, check_circular and default for writing, object_hook, object_pairs_hook, parse_float, parse_int and parse_constant for reading, and cls for a JSONEncoder or JSONDecoder subclass. loads reads bytes too. Unlike Python, ensure_ascii is off unless you turn it on, so text in other scripts is written as it is, and a set is written as a list unless default says otherwise. Bad JSON raises json.JSONDecodeError, a ValueError with CPython’s message and the pos, lineno and colno it went wrong at. With the Python standard library on, json.decoder, json.encoder and json.scanner import as well. |
re | search, match, fullmatch, findall, finditer, sub, subn, split, escape and compile, whose pattern objects have the same methods; the flags I, M, S, X (verbose: spaces and # comments in the pattern are skipped), A (\d, \w and \s match ASCII only) and U, also spelled out, or written at the start of the pattern as (?i), (?m), (?s), (?x), (?a). Patterns take lookahead (?=…) (?!…), fixed-width lookbehind (?<=…) (?<!…), backreferences \1 (?P=name), and the escapes \x41, \u00e9, \N{BULLET} and octal \101; not possessive quantifiers or atomic groups. A pattern made from bytes, re.compile(rb"\d+"), searches bytes and gives bytes back. Matching spends steps like any loop. re.Scanner(lexicon) is CPython’s small lexer: scan(text) gives what each matched action returned and the text left over. |
time | time() and monotonic() in seconds; parts() or parts(seconds), a dict of year, month, day, hour, minute, second, weekday (Monday is 0) and yearday in the phone’s time zone; format(pattern) or format(pattern, seconds) with a Unicode date pattern such as "EEE d MMM yyyy", which writes day and month names in English. Left out, seconds is now. sleep(0) returns; a longer sleep raises RuntimeError, as a plugin waits with plugin.after(seconds, fn). |
random | random, randint, randrange, getrandbits, choice, choices, shuffle, sample, uniform, seed. With the Python standard library on, it is CPython’s own random: the same numbers for the same seed, Random and SystemRandom, and gauss and the other distributions. |
sys | version, version_info (3.13, readable as .major and so on), hexversion, platform ("android"), maxsize, maxunicode, byteorder, argv, path, modules, exit, exc_info, intern, getrecursionlimit, setrecursionlimit, get_int_max_str_digits, set_int_max_str_digits, float_info, int_info, hash_info, flags, implementation, getsizeof, meta_path, prefix and base_prefix (empty), audit (which nothing listens to), and stdout, stderr and stdin. Both output streams write to the plugin’s log, a line at a time, as print does; stdin has nothing to read. Setting sys.stdout to an object with a write method sends print there. |
time.format takes the patterns Android and Java use (yyyy, MM, d, HH,
mm, EEE, MMMM and so on), not C’s %Y-%m-%d.
Limits
Section titled “Limits”Exceeding one of these is something you can see: either an error, or a note on the panel saying what had to be dropped. Two are quiet, and the table says which.
| Script size | 1 MB (256 KB up to 0.6.8rc1) |
| Archive size | 4 MB, 64 entries |
| Steps | 9M on load, 6M per event, 1.2M per render, 9M per selection action (raised from 3M, 2M, 400k and 3M in 0.6.6) |
| Time | 3 s on load, 2 s per event, 0.5 s per render, 3 s per selection action |
| Lists, dicts and sets | 10,000 items each |
| Strings | 100,000 characters |
| Recursion | 1,000 calls deep, or fewer where each call nests deep expressions (sys.setrecursionlimit raises it, up to what the native stack holds) |
| Selection action result | 64K characters |
| Widgets | 256 nodes, 12 deep, 8 tabs (dropped, and reported) |
| Widget text | 2 KB per node, 64 KB per tree (truncated, and reported) |
| Storage | 128 keys, 64 chars per key, 8 KB per value, 64 KB total |
| Reminders | 64 pending, 64 chars per id, 200 chars of text, up to ten years ahead |
| Log | 200 lines of 512 characters (truncated quietly) |
| Input box | 8 KB (truncated quietly) |
A step is one statement, one turn of a loop, or one step of a regular
expression’s matching. Going past the container, string or recursion limit
stops the call with an error that try cannot catch. A for loop or a
comprehension written over range(…) counts without building the list, so it
can go past 10,000 turns; only the step budget bounds it. list(range(…))
still builds one, and is held to the cap.
A plugin that runs out of steps or time is stopped, the user is told, and it takes a strike. So does one the watchdog has to abandon for going unresponsive. Two strikes and the plugin is switched off until they turn it back on, which also forgives the strikes. That last part is a setting: Switch off a plugin that hangs, on the Plugins screen, on by default. With it off the strikes are still counted and still shown, and only the automatic switch-off goes away.
