A Python session for Emacs, on a Jupyter kernel. You work in your .py
files, send code to the session, and get results, figures and errors back in
an ordinary Emacs buffer. The session lives on when Emacs closes.
The reference is Positron's console:
- a kernel per project;
- completion from the live objects, even while code runs;
- a plot history;
- sessions that survive a restart.
coil aims for the same experience, done the Emacs way: buffers, keys and completion that behave like the rest of Emacs.
Status: a first working version, used through a Doom config. See Status for what is tested and what is not done yet.
coil needs Emacs and a kernel, and nothing else. Everything below "Optional" it uses when it is there, and goes without when it is not: no third-party Emacs package is required.
Required
- Emacs 30.1 or later. Only Emacs's own libraries are used.
- ipykernel in the environment the kernel runs in (the project's). It
brings
jupyter_client,pyzmqand IPython, which coil's bridge uses too. Without it, coil says so, and in a pixi project offers to add it (see below). Tested with Python 3.12, IPython 9 and ipykernel 7.
Optional
| What | What it gives | Without it |
|---|---|---|
| ipykernel 7 or later | completion and docs while code runs (kernel subshells) | they wait for the running code to finish |
| pixi | the kernel in a dev environment; offers to add missing packages (at run time, as a code action, by command) |
the kernel runs in the buffer's environment; no offers |
| eglot, with a Python language server (ty, pyright, basedpyright) | the session's candidates joined to the server's completion; the add-package code action | the session's candidates where nothing else completes; the commands |
| flymake with a language server's diagnostics | coil-python-add-package knows the import at point; coil-python-add-missing-imports |
the command asks for the module |
| direnv with envrc | the project's environment for the kernel, reloaded after an install | the environment Emacs has |
| Doom Emacs | its project root | project.el's, else the directory |
Another completion source than eglot's (lsp-mode's, say) is left alone:
coil adds nothing to its answers. coil-completion-merge-with lists the
ones it joins.
- In a buffer with
coil-python-mode(yours to turn on, per buffer): its keys (python.el's REPL commands go to coil's session), a completion function ahead of the others, an eldoc function (silent unlesscoil-eldoc-in-source). - Once eglot is loaded:
jsonrpc-requestandjsonrpc-async-requestare advised. AcodeActionanswer from an eglot server, for acoil-python-modebuffer in a pixi project, gets coil's action after the server's. Every other request, and every other jsonrpc client, passes through untouched.eglot-executegets an:aroundmethod that runs coil's own action and passes every other on.
- The debugger's arrow is added to
overlay-arrow-variable-list, as gud's is. - Processes: the bridge, one per session; the kernel and its idle
watch, which outlive Emacs;
pixi, when asked. - Files: coil's state directory. In the project, only what you accept:
pixi add, and pinned figures.
(add-to-list 'load-path "~/projects/coil")
(require 'coil-python)
(add-hook 'python-base-mode-hook #'coil-python-mode)A project needs ipykernel where its kernel runs. In a pixi project, coil
offers to add it to a dev environment, not to the project's
dependencies:
ipykernel(and IPython with it) goes into[feature.dev.dependencies];- a
devenvironment is made of that feature, in the same solve group as the default one, so the packages they share have the same versions; - the kernel runs in
dev, fully activated (pixi shell-hook -e dev).
Your buffers, and the language server, keep the default environment. A
project with no dev environment runs its kernel in the buffer's own
environment. The name is coil-python-pixi-environment.
These are python.el's keys, except C-c C-c and C-c C-b.
| Key | Sends |
|---|---|
C-c C-z, C-c C-p |
nothing; goes to the session, starting it if need be |
C-c C-c |
the top-level statement point is in: all of the function, class or block (decorators, else, except too), or the line; or the region |
C-c C-b |
the buffer (with C-u, its if __name__ == "__main__" block too) |
C-c C-r |
the region |
C-c C-e |
the statement at point, or the region |
C-c C-s |
a line read from the minibuffer |
C-M-x |
the function or class at point, with its decorators |
C-c C-n |
the # %% cell at point, then moves to the next |
C-c C-l |
%run the file |
C-c C-f, C-c C-d |
nothing; shows what the session knows of the name at point |
C-c C-k |
nothing; interrupts (with C-u, restarts the kernel) |
Completion there is the language server's (eglot's), with the live
session's added: what only the running code knows, such as a data frame's
columns (df.al → alpha), a dictionary's keys (df['b → beta), and
attributes made at run time. The server's candidates keep their order,
docs and snippets. The session's come after them, with their type as
annotation and icon. The kernel is asked before the server and answers in
a millisecond or two, so the popup is not held up: measured, 1 to 4 ms in
all against eglot's 0.1 to 2 alone. When the kernel is slow (jedi's first
look at a library), its candidates join at the next key rather than being
waited for. coil-completion-in-source turns this off. Only eglot's
completion is joined (coil-completion-merge-with); another source is left
as it is, and with none, the session's candidates are offered alone. It
works with corfu or company, without cape.
With coil-eldoc-in-source, eldoc there also asks the live session (after
the language server), for what only it knows: a data frame's columns, a
value's type.
M-x run-python and any other python.el REPL command open or send to coil's
session too: they are remapped while coil-python-mode is on.
After C-c C-n, the cell's # %% line shows how it went: ✓ 0.45 s, or
✗ ZeroDivisionError: division by zero. Clicking it shows the output.
Type at the » prompt. RET runs the input when it is complete, and starts
an indented line when it is not (the kernel decides, as IPython does).
| Key | Does |
|---|---|
C-RET |
runs the input, complete or not |
C-j |
a new line |
TAB |
completes, from the live session |
| (eldoc) | the signature and summary of what is at point, from the live session: pd.read_csv(filepath_or_buffer, *, sep, …) -> DataFrame Read a comma-separated… |
M-p / M-n |
the input history, kept across restarts |
C-c C-c, C-c C-k |
interrupt (with C-u, restart the kernel) |
C-c C-n / C-c C-p |
the next / previous cell |
C-c C-o |
every figure of the project, newest first |
C-c C-q |
shuts the kernel down |
C-c C-d |
detaches: the kernel runs on; C-c C-z, or any send, attaches again |
On a cell (the output is read-only, so plain letters are free):
| Key | Does |
|---|---|
n / p |
next / previous cell |
RET |
visits the code it came from (or copies it to the prompt) |
w |
copies its output |
o |
opens its figure at full size |
c |
pins its figure, as coil-pin-function does |
P |
every figure |
TAB |
unfolds long code or output (or folds it again) |
Other commands:
coil-restart;coil-list-sessions: every kernel coil knows of, with its pid, memory, uptime, and whether this Emacs is attached.RETattaches to one (or starts it) and shows it,ddetaches,kkills,glooks again;coil-trustandcoil-untrust;coil-python-add-missing-imports, which offers each import the language server cannot find.
Each run ends with a hairline across the window. Its code sits on a faint
tint (coil-code) and its output on the plain page, with the status at the
right edge. Code of more than coil-fold-input-lines lines (12), as from a
large paste, shows its first coil-fold-input-shown (6), then … N more lines TAB. Output folds after coil-fold-lines (200).
It is IPython's debugger (pdb), in the session's own kernel, so everything the session has defined is there to look at. coil follows it in the source, as edebug does.
Key (in a .py buffer) |
Does |
|---|---|
C-c C-x x |
runs the cell (or region) and stops at this line; with C-u, at its first |
C-c C-x b |
sets a breakpoint on this line, or takes it away |
C-c C-x B |
takes away every breakpoint of the buffer |
C-c C-x d |
opens the debugger where the last error was raised (%debug) |
C-c C-x e |
has every error open the debugger, or no longer (%pdb) |
In the session, d on a failed cell does the same as C-c C-x d.
Where it stopped has an arrow in the fringe, and the line is highlighted. That buffer takes single keys while it is stopped:
| Key | Does |
|---|---|
n, SPC |
next line, over calls |
s |
step into the call |
c |
continue, to the next breakpoint or the end |
r |
on to the end of this function |
u / d |
up / down the stack (the arrow follows, into other files too) |
e |
the value of the name at point, or of the region, in the echo area; C-u e asks for an expression |
RET |
on to this line |
b |
a breakpoint here, or not (the debugger is told at once) |
w |
the stack, in the session |
q |
quit; what was running stops too |
? |
these keys |
The session's prompt becomes ipdb> while the debugger waits. Type anything
pdb takes there: pp vars(), !x = 3, interact.
Breakpoints are marks, not code. No breakpoint() line goes into the
file. Every run started while there are breakpoints stops at them, wherever
they are:
- in the cell being sent;
- in a function sent before, from any buffer;
- in a module of the project that the code imports;
- under
%run.
Runs with no breakpoints anywhere are not traced, so they run at full speed.
How it works:
- ipykernel runs each cell as a file named after a hash of its code. pdb shows that file.
- The bridge computes the same name for every code it sends (event
codefile). coil remembers which lines of which buffer each name was, and maps pdb's place back to them. - For a run with breakpoints, the bridge first installs
bridge/coil_debug.pyin the kernel. It does this silently, as a module of its own, so no names appear in your namespace. The bridge tells it the breakpoints. coil_debug.pysets them as pdb breakpoints when IPython is about to run that cell. The cell is sent exactly as written.- Tracing starts there and ends when the cell ends.
- IPython runs a cell's last expression as code of its own. Stepping off the end of one part goes on to the next part, not into IPython.
Limits:
- A cell with a cell magic (
%%time) runs its body elsewhere, so breakpoints inside it are not met. - If the buffer is edited after code is sent, a breakpoint on the old lines can stop on the wrong line until the code is sent again.
.py buffer ──┐
├── coil.el ══ pipe, JSON lines ══ coil_bridge.py ══ ZMQ (ipc) ══ ipykernel
session buf ─┘ (Emacs) (project env) (project env,
detached)
- Kernel.
ipykernel, started by the bridge in the project's environment.- The environment is the one of the buffer the session was started from: with envrc and direnv, the project's.
- The kernel runs detached, in its own session and process group, so it outlives the bridge and Emacs.
- Bridge.
bridge/coil_bridge.py, about 600 lines onjupyter_client(whichipykernelbrings).- Emacs runs it as a plain subprocess, with
python -I, so nothing in the project directory can shadow its imports. - It attaches to the project's kernel if one is alive, or starts one.
- It speaks JSON lines on stdin and stdout and listens on nothing.
- When Emacs goes, it goes; the kernel stays.
- Emacs runs it as a plain subprocess, with
- Completion while code runs. Completion, docs and
is_completeare asked on a kernel subshell (JEP 91, ipykernel 7), which answers while the main shell is busy. Measured: 0.04 s during a runningtime.sleep. - Emacs side. Plain functions over the bridge's messages; no EIEIO, no monads, no native module.
Why ipykernel, not an instrumented plain Python. IPython's kernel brings, all of them needed:
- the display protocol (pandas, PIL and matplotlib figures);
- its completer (filenames inside strings, too);
- subshells, interrupt and
input(); - readable tracebacks, and
%run,%debugand%timeit.
The protocol between Emacs and the bridge is coil's own, so a lighter backend could replace bridge and kernel later without the Emacs side changing.
coil.el: sessions, the session buffer, sending code, completion, figures, the log. Nothing in it knows about Python.coil-python.el: Python's part:- the interpreter and kernel, from the buffer's environment;
- python.el's keys and
# %%cells; - pixi: adding
ipykerneland missing packages.
coil-debug.el: the debugger. It takes pdb's prompt and marks where pdb stopped, adds the stepping keys and the breakpoints, and opens post-mortem.bridge/coil_bridge.py: the bridge. It speaks the Jupyter protocol, not Python, so it can drive any kernel. It also names the cells as ipykernel does, when ipykernel is there.bridge/coil_debug.py: the breakpoints, inside the kernel.
Another language later means another coil-<language>.el.
coil does not know about canvases, slide decks or folders of figures. It offers:
coil-pin-function, called bycwith a figure's image file and its cell;coil-figure-functions, run with the session, the cell and the image file of every figure as it is drawn;coil-cell-done-functions, run with the session and the cell when a cell ends;coil-input-request-functions, which may take a question from the kernel (input(), pdb's prompt) rather than leave it to the minibuffer, andcoil-askandcoil-answerto ask it at the session's prompt;coil-breakpoints-function, which says where a run is to stop.
The Doom config that uses coil pins figures to canvacs canvases with these:
the figure goes to figures/NAME.png in the project and becomes an image
card whose source is the script, and a re-run rewrites the file.
- One kernel per project root:
doom-project-root, elseproject.el's root, else the directory. - Starting. The first send, or
C-c C-z, starts the bridge. It attaches to the project's kernel if one answers, and starts one if not. Sends made meanwhile wait in a queue. - Surviving. The kernel is started in its own session and process group, with nothing tying it to the bridge, so it lives on when the bridge or Emacs ends. Its connection file, pid and log stay in coil's state directory, and that is how a later Emacs finds it again.
- Ending when idle. A kernel that has run nothing for
coil-kernel-idle-hours(48) is shut down; nil keeps it forever.- Since a kernel outlives Emacs, this is kept by a small watch process
started beside it (
coil_bridge.py --watch), detached as the kernel is. It ends with the kernel. - The watch listens to the kernel's broadcasts, where every client's runs are announced. Before shutting down, it checks that the kernel answers at once, so a run longer than the limit, or one begun before the watch, is never cut short.
- The session says why the kernel went, if attached, and the next session of the project does too. The log is kept; the variables are lost.
- Since a kernel outlives Emacs, this is kept by a small watch process
started beside it (
- History.
- Each cell is logged as it ends: its code, source, timing and outputs, with figures as PNG files.
- A new session buffer is rebuilt from the log, the last
coil-log-cellscells of it. - A new kernel starts a new log;
coil-log-keepold ones are kept, and figures no kept log refers to are deleted.
- At run time: a
ModuleNotFoundErroroffers to add the package to the pixi project: "No module named sklearn. Add scikit-learn to …?" with the choices conda-forge, PyPI or no. - On yes:
pixi addruns in the background;- the project's buffers reload their environment;
- coil asks whether to run the cell again. A running kernel imports a newly installed package without a restart.
- The lookup (
pixi search, which says whether conda-forge has the package) runs in the background, and the question comes when it is done, so Emacs is never held up. Packages found are remembered for the Emacs session. Several offers are looked up at once and asked one at a time. - Before running, as a code action: on an import the language server
cannot resolve, eglot's code actions (
M-x eglot-code-actions, or its ⚡ hint) include "Add the package for sklearn to the pixi project (coil)". It makes the same offer.coil-python-code-actionsturns it off. - Before running, by command:
coil-python-add-package(the import at point, or one you name) andcoil-python-add-missing-imports(every one in the buffer). - Which diagnostics: those whose message says an import cannot be
resolved: ty's "Cannot resolve imported module
x", pyright'sImport "x" could not be resolved. Matched by message, with case, not by rule name, which servers rename. "Modulexhas no membery" is not one. - Import names:
coil-python-packagesmaps the ones whose package is named otherwise (sklearn→scikit-learn,cv2→opencv, …).
Kernel output, files read by code, and packages are all untrusted.
Text printed by code can carry terminal escape sequences, and a crafted file or web response can carry anything. (The comint-mime hole found in the setup coil replaces was this: an escape sequence in printed text made Emacs read or delete an arbitrary file.)
- Output reaches Emacs only as Jupyter messages, already split into stream text, MIME bundles and errors.
- In text, only colour sequences (SGR) are applied. Other CSI sequences are dropped, and any other escape stays as visible text. Nothing is acted on.
- Drawn:
image/pngandimage/jpegonly, through Emacs's image libraries. - Never drawn: HTML, LaTeX, SVG and JavaScript. HTML can reach the
network, LaTeX runs TeX, and SVG can reference other files. The bridge
drops them; only their
text/plainalternative is shown. - Size limits: 50 MB per message (in the bridge), and a PNG of more
than
coil-max-image-pixelsis not drawn. Emacs's ownmax-image-sizeapplies as well. - No file path ever comes from the kernel. Images arrive as data.
Whoever can talk to a kernel can run code as you.
- The kernel listens on Unix sockets (the
ipctransport) in a directory only you can open (0700). - Messages are signed with a fresh 256-bit HMAC key per kernel.
write_connection_filedefaults to an empty key; the bridge always passes one. - Connection files are 0600, in
$XDG_STATE_HOME/coil/<project hash>/. They are outside the project, so they are never committed or synced with it. - The bridge listens on nothing; it is reached only through its pipe.
- The idle watch listens on nothing either. It is a client of the kernel,
through the same connection file, and only reads the broadcasts, asks
kernel_info, and asks for shutdown. - One exception, from ipykernel: it always opens a port on
127 8556 .0.0.1so that output from forked subprocesses reaches the session (IOPubThread(pipe=True), hard-coded).- It accepts output only, never code, and only with a random 16-byte token.
- What it forwards is checked against the kernel's HMAC key by the bridge.
- Checked with
lsof: it is the kernel's only network socket.
Starting a kernel runs code from the project: pixi activation scripts, .pth
files, sitecustomize, IPython startup files.
- coil starts a kernel only in a project you have trusted. It asks once, and
keeps the answer in
trusted.eldin its state directory. coil-untrustrevokes it. The Doom config counts accepting its.envrcoffer as the same trust.
pixi add of a name taken from code is a typosquatting risk: a malicious or
misspelt import in a cloned repo could get a hostile package installed.
- Nothing is installed without asking. The prompt names the exact package and where it comes from.
- conda-forge is the default; PyPI only on an explicit choice.
- A name not found on conda-forge gets a warning, and no conda-forge choice: "Check the name: a misspelt or planted import can install a hostile package."
- A name guessed from the import, rather than known from the table, is said to be a guess.
- An install changes
pixi.tomlandpixi.lock, so it shows ingit diff.
Outputs can contain secrets: tokens, data, personal information.
- The log and its figures are 0600, in the state directory, outside the project.
coil-log-keeplimits how many are kept; nil keeps none.- Only pinning writes into the project (through
coil-pin-function).
- Code you choose to run. Running a cell runs code as you; coil is not a sandbox.
- Other processes running as you. They can read your files and sockets anyway.
- A malicious project you have trusted.
Tested by hand, on a pixi project with IPython 9 and ipykernel 7:
- the bridge's lifecycle: start, execute, error, figure,
input(), completion, interrupt, detach and reattach with state kept, shutdown that cleans up its files; - the security properties above, including the
lsofcheck; - the session buffer:
- cells, colour tracebacks and figures;
RETdeciding between running and a new line;- completion of members and of filenames in strings, also while a cell runs;
- interrupt;
# %%cells and their summaries;- the missing-import offer, for a known name and for a misspelt one;
- restart and shutdown;
- closing Emacs and reattaching to the same kernel, with the history rebuilt from the log.
- completion in a
.pybuffer, merged with eglot's on ty: the live session's candidates added (a data frame's columns, a dictionary's keys) and the latency measured against eglot alone; - the idle watch: an idle kernel shut down attached and detached, a run longer than the limit left alone, and the next session told why;
- the conda-forge lookup in the background: offers asked one at a time, a misspelt name warned of and not offered from conda-forge;
- the add-package code action, with ty 0.0.104 in eglot: listed after ty's
own action on an unresolved import, none on other lines, and run through
eglot-execute; - pinning to a canvacs canvas through the Doom config's
coil-pin-function, and a re-run rewriting the pinned figure.
make test-elisp # the Emacs side, kernel stubbed: needs only Emacs
make test-bridge PYTHON=env/bin/python # the bridge with a real kernel: a Python with ipykernel
make compile # byte-compiles, warnings as errorstest/coil-test.el covers completion merged with another source (order,
metadata, exit functions, a late kernel answer, dictionary keys, stepping
aside for a source not listed), the idle-shutdown note, which diagnostics
mean a missing package, the code action (built, run, and kept from
non-eglot connections), and the queue of missing-package offers.
test/test_bridge.py runs a real kernel: completion of live objects, and
the idle watch with a limit of 8 s (COIL_TEST_IDLE), attached, detached,
during a run longer than the limit, and turned off. It takes about a minute,
and is skipped where ipykernel is not installed.
GPL-3.0-or-later. See LICENSE.