This post was AI-translated from the Japanese original.

I wrote a small terminal emulator in Rust called termlet. It opens a window, runs your shell, runs Emacs without trouble, and lets you scroll back with the mouse wheel, and that’s about it. It fits in roughly 1,000 lines. It’s Linux only.

I started it because I wanted to know what the terminal emulator I use every day is actually doing. I wrote it with Claude Code teaching me along the way.

It fits in 1,000 lines because I didn’t write the hardest part of a terminal emulator myself: parsing escape sequences and managing the screen grid. That’s left to alacritty_terminal, and termlet is only the code around it. This post goes through it in order, from an empty window to running Emacs.

Overview

The terminal, the kernel and the shell

Before getting into termlet, it’s worth sorting out how a terminal emulator and a shell talk to each other.

They aren’t connected directly. Between them sits a PTY (pseudo-terminal) in the kernel. A PTY is something like a bidirectional pipe with two ends, the master and the slave. The terminal emulator holds the master, and the shell runs with the slave as its standard input, output and error. To the shell, the slave is an ordinary terminal device (/dev/pts/N).

   termlet                    kernel (PTY)                      shell
+----------+     +--------------------------------------+     +-------+
| keyboard |---->| master --> line discipline --> slave |---->| read  |
|          |     |              (echo)                  |     |       |
| screen   |<----| master <-- line discipline <-- slave |<----| write |
+----------+     +--------------------------------------+     +-------+

Between the master and the slave sits a kernel layer called the line discipline. This is where the terminal-like behavior lives: it holds input until a line is complete, echoes what you type, sends a signal on Ctrl+C, and converts newlines. How it behaves is controlled by the termios settings you can see with stty.

As an example, let’s follow what happens when you type echo 'hi' at a prompt and press Enter. Assume the shell isn’t using readline (line editing), so the line discipline is in the mode where it holds whole lines (canonical mode).

  1. When you press e, termlet writes the single byte e to the master. termlet draws nothing on the screen at this point
  2. The line discipline puts e into its line buffer. The shell is still blocked in read() on the slave and hasn’t received anything
  3. Since ECHO is on, the line discipline sends e back to the master side. termlet reads it from the master and draws e on the screen
  4. The rest, cho 'hi', goes the same way. If you press Backspace (0x7f) along the way, the line discipline removes a character from its line buffer and echoes \b \b to erase it from the screen. The shell still knows nothing
  5. When you press Enter, termlet writes \r. The line discipline turns \r into \n (ICRNL), and since the line is now complete, the shell’s read() returns with echo 'hi'\n. The newline is echoed as \r\n (ONLCR)
  6. The shell runs echo and writes hi\n to the slave. On the output side, the line discipline turns \n into \r\n as well, and termlet reads hi\r\n from the master and draws it. Then the shell writes the next prompt, $

When I checked this by running bash --noediting on a PTY, e came back from the master as soon as I wrote it, while the shell was still blocked in read(). After Enter, this is what I could read from the master:

\r\nhi\r\n$ 

That’s the echoed newline, the output of echo, and the next prompt, in that order.

Ctrl+C is handled by the line discipline too. termlet just writes the single byte 0x03, and the line discipline sends SIGINT to the terminal’s foreground process group (ISIG). Which processes get it depends on the session that has the terminal as its controlling terminal, which is why setsid() and TIOCSCTTY, coming up later, are needed. If you press Ctrl+D at the start of a line, the shell’s read() returns 0 bytes, and the shell treats it as EOF and exits.1

Looking at it with ps

You can see these relationships from outside with ps and /proc while termlet is running. Here, bash inside termlet is running sleep 300 | cat.

$ pstree -p -T $(pgrep termlet)
termlet(1001746)---bash(1001758)-+-cat(1001766)
                                 `-sleep(1001765)

termlet started bash, and bash started sleep and cat. That’s all there is to the parent-child relationships. The relationship to the PTY shows up in ps.

$ ps -o pid,ppid,pgid,sid,tty,tpgid,stat,comm -p 1001746,1001758,1001765,1001766
    PID    PPID    PGID     SID TT         TPGID STAT COMMAND
1001746 1001704 1001704 1001704 ?             -1 SNl  termlet
1001758 1001746 1001758 1001758 pts/31   1001765 SNs  bash
1001765 1001758 1001765 1001758 pts/31   1001765 SN+  sleep
1001766 1001758 1001765 1001758 pts/31   1001765 SN+  cat
  • bash is a session leader, with an SID equal to its own PID (the s in STAT), and has pts/31 as its controlling terminal. That’s the result of setsid() and TIOCSCTTY, which come up later
  • termlet’s TT isn’t pts/31. termlet only holds the master side, and pts/31 isn’t its controlling terminal. It shows ? here because I started termlet directly rather than from a terminal; start it from another terminal and that terminal shows up instead
  • sleep and cat are in the same process group (PGID), and that group is the foreground process group of pts/31 (TPGID). The + in STAT also means foreground. If you press Ctrl+C now, the line discipline sends SIGINT to this process group, that is, to sleep and cat. bash doesn’t get it

(The N in STAT is there because processes ran at a lower priority in this environment. It has nothing to do with termlet.)

You can tell the master from the slave by looking at the file descriptors in /proc.

$ ls -l /proc/1001746/fd | grep ptmx
lrwx------. 1 masahiko masahiko 64 Nov 11 15:10 13 -> /dev/ptmx
lrwx------. 1 masahiko masahiko 64 Nov 11 15:10 14 -> /dev/ptmx
$ grep tty-index /proc/1001746/fdinfo/13
tty-index:	31
$ ls -l /proc/1001758/fd
lrwx------. 1 masahiko masahiko 64 Nov 11 15:10 0 -> /dev/pts/31
lrwx------. 1 masahiko masahiko 64 Nov 11 15:10 1 -> /dev/pts/31
lrwx------. 1 masahiko masahiko 64 Nov 11 15:10 2 -> /dev/pts/31

What termlet holds is /dev/ptmx, the master side. There are two because termlet duplicates it for the thread that reads the PTY. Every master shows up as /dev/ptmx, so to see which slave one is paired with, look at tty-index in fdinfo. Here it’s 31, meaning /dev/pts/31. bash’s standard input and output are connected to that /dev/pts/31.

How termlet is put together

These are the only crates it depends on.

Crate Role
winit Window and event loop
glutin / glow OpenGL context and drawing
rustix System calls: PTY, termios, setsid and so on
alacritty_terminal Parsing escape sequences, and the screen grid
crossfont Font rasterization

The data flows like this.

keys ──> keys::encode ──> PTY ─────────────────────> shell / Emacs
                                                     │
screen <── render <── Term <── Processor::advance <──┘

When the bytes the shell wrote are passed to alacritty_terminal’s Processor::advance, the grid inside Term is updated. Drawing just reads the cells out of Term every frame, and the drawing side doesn’t hold the screen contents.

Writing your own escape sequence parser would probably take several thousand lines by itself. The vte crate (0.15.0) that alacritty_terminal uses is 4,144 lines on its own. Not having to write that is the biggest win.

An empty window

The first step is just opening a window and filling it with a single color. It’s unexciting, but it’s also where most of the unknowns are. If the combination of compositor, GPU driver and crate versions doesn’t work, it’s cheaper to find out before getting into PTYs and escape sequences.

winit runs the event loop, glutin creates the OpenGL context, and glow does the filling.

impl ApplicationHandler for App {
    fn resumed(&mut self, el: &ActiveEventLoop) {
        // Create the window, the GL context and the surface here.
    }

    fn window_event(&mut self, el: &ActiveEventLoop, _: WindowId, ev: WindowEvent) {
        match ev {
            WindowEvent::RedrawRequested => {
                unsafe {
                    gl.clear_color(0.08, 0.09, 0.11, 1.0);
                    gl.clear(glow::COLOR_BUFFER_BIT);
                }
                surface.swap_buffers(context).unwrap();
            }
            WindowEvent::Resized(size) => {
                if let (Some(w), Some(h)) =
                    (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
                {
                    surface.resize(context, w, h);
                    unsafe { gl.viewport(0, 0, w.get() as i32, h.get() as i32) }
                }
            }
            WindowEvent::CloseRequested => el.exit(),
            _ => {}
        }
    }
}

Opening a PTY and starting the shell

Next, open the PTY from the overview and start the shell on it.

let master = rustix::pty::openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY)?;
rustix::pty::grantpt(&master)?;
rustix::pty::unlockpt(&master)?;
let name = rustix::pty::ptsname(&master, Vec::new())?;
let slave = rustix::fs::open(&name, OFlags::RDWR, Mode::empty())?;

let mut cmd = Command::new(shell);
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
let sfd = slave.try_clone()?;
unsafe {
    cmd.pre_exec(move || {
        rustix::process::setsid()?;
        rustix::process::ioctl_tiocsctty(&sfd)?;
        rustix::stdio::dup2_stdin(&sfd)?;
        rustix::stdio::dup2_stdout(&sfd)?;
        rustix::stdio::dup2_stderr(&sfd)?;
        Ok(())
    });
}

In the child, setsid() creates a new session first, and then TIOCSCTTY makes the slave its controlling terminal. Only a session leader without a controlling terminal can call TIOCSCTTY, so the order can’t be swapped.

The tricky part is that if you forget TIOCSCTTY, everything still works when the shell is bash. bash reacquires a controlling terminal by itself at startup, so you don’t notice the mistake. That’s why termlet checks the master’s foreground process group with tcgetpgrp() after starting the shell, to make sure the child really got the controlling terminal.

The PTY’s size is set with TIOCSWINSZ before spawn(), because the shell reads the terminal size when it starts.

COLORTERM=truecolor is needed too. The xterm-256color terminfo entry doesn’t have the 24-bit color capability, so without it, Emacs and others round colors down to 256.

Drawing the screen

The PTY is read on a separate thread. It sends what it reads to the main thread over a channel and wakes the event loop with EventLoopProxy::send_event. The main thread feeds the bytes into Term with Processor::advance and requests a redraw.

Drawing is very simple. It goes through the cells that term.renderable_content() returns, one by one, and draws a rectangle for the background and a texture for the character.

for cell in content.display_iter {
    let line = cell.point.line.0 + offset as i32;
    let col = cell.point.column.0;
    let (x, y) = (col as i32 * cw, line * ch);
    let c = cell.cell;
    let (mut fg, mut bg) = resolve(c.fg, c.bg, c.flags, &self.palette, colors);
    if cursor.is_some_and(|p| p.line == line as usize && p.column.0 == col) {
        fg = bg;
        bg = named(NamedColor::Cursor);
    }
    if bg != default_bg {
        let w = cw * (1 + c.flags.contains(Flags::WIDE_CHAR) as i32);
        r.fill(x, y, w, ch, bg);
    }
    if !c.flags.contains(Flags::WIDE_CHAR_SPACER) {
        glyphs.push((c.c, c.flags.contains(Flags::BOLD), x, y, fg));
    }
}
r.begin_glyphs();
for (c, bold, x, y, fg) in glyphs {
    r.glyph(c, bold, x, y, fg);
}

Scrollback is almost entirely handled by alacritty_terminal. When the wheel turns, termlet just calls term.scroll_display(). renderable_content() returns the cells at the scrolled position, so the drawing side doesn’t change at all.

Turning key presses into bytes

Key presses are turned into the bytes applications expect and written to the PTY. Most of it is what you’d expect, but a few things will catch you if you don’t know them.

  • Enter is \r, not \n
  • Backspace is 0x7f
  • Ctrl plus a letter is the character code ANDed with 0x1f (C-c is 0x03)
  • Alt puts ESC in front of the key (M-x is ESC x)

Arrow keys can be sent in two ways. Normally it’s CSI A (\e[A), but once an application turns on a mode called DECCKM, you have to send SS3 A (\eOA) instead. vim and Emacs apparently use this mode, so if you ignore it, the arrow keys stop working. Term keeps track of the mode, so it’s just a matter of checking term.mode().

fn cursor_key(c: u8, mods: ModifiersState, app: bool) -> Vec<u8> {
    let m = modifier_param(mods);  // 1 + Shift + Alt*2 + Ctrl*4
    if m > 1 {
        format!("\x1b[1;{m}{}", c as char).into_bytes()  // C-→ is \e[1;5C
    } else if app {
        vec![0x1b, b'O', c]
    } else {
        vec![0x1b, b'[', c]
    }
}

Arrow keys with modifiers (C-→ and so on) are sent as CSI 1;<modifier> X regardless of the mode.

Running Emacs

At this point the shell and vim work. Emacs needs one more thing, though: answering the application’s queries.

For example, at startup Emacs sends a query called DA2 (Secondary Device Attributes) to ask for the terminal’s type and version, and decides which features to use based on the answer. In Emacs 30.2’s xterm.el, a version of 216 or higher turns on modifyOtherKeys, and 242 or higher makes it ask for the background color. If no answer comes back, it waits for a timeout (2 seconds by default) and runs without either.

Fortunately, Term already answers DA1/DA2 and the cursor position query (DSR). It answers DA2 with \e[>0;2600;1c. 2600 comes from alacritty_terminal’s version, 0.26.0, and is above both 216 and 242. The answers are handed to the EventListener as Event::PtyWrite, so all termlet has to do is write them back to the PTY.

impl EventListener for ToPty {
    fn send_event(&self, ev: Event) {
        let bytes = match ev {
            Event::PtyWrite(s) => s.into_bytes(),
            Event::ColorRequest(i, f) => f(self.palette.index(i)).into_bytes(),
            Event::TextAreaSizeRequest(f) => f(self.size.get()).into_bytes(),
            _ => return,
        };
        let _ = self.tx.send(bytes);
    }
}

Only the background color query (OSC 11) and the window size query (CSI 14t) arrive as ColorRequest and TextAreaSizeRequest instead of PtyWrite. Each comes with a function that builds the answer from a value you give it, so termlet passes it the palette color or the window size. ToPty only sends the answers over a channel; the main thread writes them to the PTY all at once, after it has fed the output into Term. Once termlet answers OSC 11, Emacs knows the background is dark and picks colors for a dark background.

modifyOtherKeys

To use C-; or C-, in Emacs, you need something called modifyOtherKeys. There’s no control character for C-;, so an ordinary terminal just sends ;. After it sees the answer to DA2, Emacs sends \e[>4;1m to ask the terminal to turn modifyOtherKeys on, and from then on C-; arrives as \e[27;5;59~.

Term, however, doesn’t implement modifyOtherKeys. Of the 71 methods in Handler, Term implements 66, and the two for modifyOtherKeys (set_modify_other_keys and report_modify_other_keys) aren’t among them. So termlet looks at the bytes before passing them to Processor::advance, picks out \e[>4;Nm, and keeps the state itself. The bytes arrive in whatever chunks were read from the PTY, and a sequence can be cut in the middle, so this is a small state machine. Once it has collected the parameters of a CSI sequence, it decides like this:

fn finish(&mut self, reply: &mut Vec<u8>) {
    match self.buf.as_slice() {
        b">4" | b">4;0" => self.mode = 0,
        b">4;1" => self.mode = 1,
        b">4;2" => self.mode = 2,
        b"?4" => reply.extend_from_slice(format!("\x1b[>4;{}m", self.mode).as_bytes()),
        _ => {}
    }
}

CSI ? 4 m asks for the current mode, so termlet answers that too. On the key input side, mode 1 sends only keys that have no control character (like C-;), and mode 2 sends every character key with Ctrl or Alt, as CSI 27 ; modifier ; character code ~.

Limitations

  • Linux only. It uses winit features for Wayland and X11, so it doesn’t build on macOS or Windows
  • The mouse only scrolls back with the wheel. No selection, no copy
  • No pasting from the clipboard
  • No IME support, so you can’t type Japanese (it displays fine)
  • Drawing isn’t optimized. No glyph atlas and no damage tracking
  • No configuration file. The font (JetBrains Mono, 15px) and the colors are hard-coded
  • No tabs or splits

Wrapping up

The source is on GitHub, under the MIT license.

  1. bash normally uses readline, and turns off ICANON and ECHO while it waits at the prompt. In that case bash itself holds the line and does the echoing, and the line discipline passes input to bash byte by byte. Ctrl+C handling (ISIG) and newline conversion on output (ONLCR) stay on. The terminal emulator can’t see the difference, though. Either way, termlet turns keys into bytes and writes them to the master, and draws whatever comes back from the master. It doesn’t need to know who’s doing the echoing. ↩