terminal.doc: a Word document that is a terminal emulator
Published: 2023-05-29
This blog post is also available as a video series! Watch it on
YouTube: Part 1 | Part 2
I decided to make a Word document that is also a terminal emulator. It doesn't have any practical purpose, I just made it for fun.
The first video linked above (Part 1) is a demo of me using the terminal emulator.
If you want to try this for yourself, you will need to be running Microsoft Word on Windows 10 or 11. You'll then need to download the terminal emulator document, open it in Word, and allow the macros to run.
This blog post explains how that document works.
The short answer
Some of you have predicted this already. It uses VBA scripts in the document, which load some kernel API functions from some Windows DLLs, and uses them to launch and interact with programs.
The long answer includes some interesting challenges though, and that's what the rest of this blog post is about.

What makes a terminal emulator?
There's three important parts to a terminal emulator. There's:
- a parser for the incoming data stream, from the program that is connected to the terminal, which determines how to update the terminal's text buffer.
- a renderer to turn that buffer into something that can be displayed on the screen.
- And finally there's a keyboard encoder which takes keyboard input data and turns it into a data stream to send to the connected program.

The keyboard encoder part is normally very simple. Any modern OS provides keyboard input through a convenient abstraction layer. For most key presses, the terminal emulator just passes the character from the keyboard event directly to the program. Sometimes it needs to be a bit more sophisticated, though. For example arrow keys get turned into special control sequences.
The renderer part is the next most complicated part, as it requires interacting with graphics hardware. Again, modern OSes provide good abstraction layers for graphics output, but generally this part is still more complicated than input.
Finally, the parser for incoming data is the most complicated part. It is, in my opinion, what defines what a terminal emulator is. If you don't do this step and just put all the text on the screen without parsing it, then you wouldn't have a terminal emulator, you'd just have a thing that displays a raw data stream.
So these are the three things I needed to have in my terminal emulator. Now, over to Word. I'm sure the first question some of you had after seeing the demo was "how is this even possible inside a word document? Word documents are just static blobs of data, they don't contain code!"
Well, actually they can contain code. Microsoft's Visual Basic for Applications, AKA "VBA", is a lighter weight version of Visual Basic that Microsoft has embedded into many of the applications that they offer. It enables application functionality to be augmented by the user, or by other developers, without them needing to have the source code for the application itself. This is a really powerful tool for building useful things on top of existing code.
In the case of VBA in Word: the code that you wrote would be stored inside of a Word document or a template file, and would be available to anyone using that file. In Word, it is typically used to generate parts of documents. The classic example is mail merge, where you want to generate a bunch of letters and print them out and mail them to people given a database of names and addresses.
There is a big downside to this though. Allowing people to embed computer code into Word documents is risky. Suppose I write some VBA code that starts sending all the contents of your Documents folder over the internet to a web server that I own. Now I just need to email you a word document, and once you open it I start receiving confidential files.
By default, modern versions of Microsoft Word will not execute VBA code embedded in documents. There are modern alternatives to VBA that are much safer for the user, and so these are preferred instead. Of course, Microsoft doesn't want to break compatibility with older documents, so Word will ask you if you want to allow macros to run.
The reason why I'm using VBA for this instead of the modern MS Word extension API is because it's far more entertaining to have a Word document be a terminal emulator than it is to have a Word extension that's a terminal emulator. It's almost too easy if it's an extension. The VBA method also means I can share just a single Word file with everyone and it "just works" with no plugins to install.
The Technical Details
So how does this actually work?
1. Text Buffers and Rendering
Normally a terminal emulator would maintain buffers in memory that contain details about the text to put on the screen. Typically there is a buffer for text, and another buffer for formatting attributes. Then the rendering code takes the contents of these buffers and produces the final image you see on the screen.
In the case of my Word document terminal, I wanted to use the existing rendering features in Word. Since Word already has its own internal buffers for keeping text and formatting information around, I wanted to simply reuse these. This is one of the things that I did to make the task deliberately more difficult. It's more difficult because the user is able to directly interact with this buffer at the same time as my code does. If I was maintaining my own buffers then there would be much less opportunity for race conditions and mismatches in internal state.
You see, when my code needs to add to this buffer, or rather: add to the document, it needs to determine somehow where in the document to insert the new text, insert it there, set any attributes on it, and make sure that the cursor ends up in the right place.
It's hard to be sure if the cursor is already in the right place. The user can move the cursor in various ways. They can use arrow keys, click somewhere else in the document, or perhaps implicitly move the cursor by deleting or pasting in text. All of these actions are handled by Word directly, and not from my code. My code just has to deal with the consequences of them. In practice, the way that I deal with this problem is by ignoring it, mostly.
While my code will move the cursor if required by a specific control sequence from the program, it otherwise just allows the user to move it, and inserts new text wherever the cursor happens to be. The reality is that this is good enough for most use cases. (As if there are any real use cases for a terminal emulator in a Word document.) This is part of the reason why vim doesn't work very well in this terminal emulator. Vim explicitly moves the cursor around a lot, and expects it to remain wherever it puts it until it moves it again. If the user has moved the cursor in the meantime, then vim's rendering logic fails.
So, my terminal emulator is using the document as its buffer. This means that I get to entirely skip writing the rendering part of a terminal emulator, since Word is doing that for me.
2. Handling Keyboard Input
Word already does a bunch of things in response to keyboard input. One thing that it doesn't do, however, is provide VBA code with a way to listen to keyboard input events.
It is technically possible to receive keyboard events from a Form in VBA code, but that's not applicable here because I want this to work in the normal document pane. Since I can't receive the keyboard events from Word, I have to derive keyboard events from the effects that they had on the document.
I do this by using an infinite loop that repeatedly checks the document for changes and determines what was the most likely cause of the change.
For example: suppose in one iteration of my main loop I see that the previous state of the document was when it was 23 characters long in total, but now I see that in its current state it is 24 characters long. The document has one more character in it than it did before. I assume that this is because the user has typed a character. It's possible that they typed multiple characters between the times that I checked, and so perhaps it is 25 or 26 characters long. Regardless, I can determine how many new characters have appeared, and extract that number of characters from directly behind the current cursor position in the document.
Surprisingly this is actually quite effective. Similarly I can detect when the document gets shorter, and I can assume that this is the result of the user pressing backspace. I can then insert backspace characters into the input stream for the connected program.
I could also observe changes in the cursor position that don't correspond to changes in document length, and use those to deduce when the user has pressed arrow keys to move the cursor. In practice though, this is too complicated to be worthwhile. Naturally, the user can achieve the same effect in the document via multiple different means, so I cannot perfectly map document changes onto the keyboard events that produced them.
The theme of this project was deliberately making things hard for myself, and in this case I actually made things impossible for myself. Did the user just type "hello" by pressing H E L L O? or did they paste in the word hello with Ctrl-V? There is no way I can know. Similarly, if a keyboard action has no effect on the document, then I can't detect it. This is why I can't detect Ctrl-C and send an interrupt to the program.
This is acceptable, however. The benefit of writing a tool simply for entertainment purposes is that bugs that produce comically bad user experiences are actually features.
Okay, so I kinda have keyboard input. It's a bit janky, but it's good enough. Now all I need is a parser for terminal escape sequences.
3. Parsing Escape Sequences
This is the actual terminal emulator part. And actually this is the really boring part of the whole thing. Honestly I don't have much to say about it. It works as you would expect. The only strange thing it is doing is interacting with Word to maintain the resulting state, instead of maintaining its own buffers.
It moves the cursor around the word document instead of maintaining its own cursor position. It puts text directly into the document instead of buffering it itself. Again, there's a bit of jankiness here, but it works well as an entertainment piece.
The cursor doesn't move around exactly as expected. It struggles to delete the right sections of text when it needs to overwrite something that's already there. It takes a long time to complete certain actions. But it's fine! I could have spent more time on it and probably gotten Vim to be almost usable like this, but I decided to just leave it. It was entertaining already.
And then the other little annoying bits
Now onto some strange little things that came up while I was writing this.
First of all, you probably saw in the other video that Vim doesn't believe it's connected to a terminal. I joked about Vim being rude, but actually it's technically correct. You see, for historical reasons that I don't fully understand, some programs care about if they are connected to a terminal or not. Most modern OSes provide a mechanism for a program to query "hey am I connected to a terminal?", and since we have terminal emulators, the OSes also have to provide a way for a terminal emulator to tell the OS "hey, I'm a terminal emulator, if this program asks if it's connected to a terminal, say yes!".
If you want to read about how Linux handles this, have a read of the documentation for the ioctl tty syscalls (man ioctl_tty). You can also open a process on a pseudoterminal device as documented in man pty.
Windows handles this very differently, of course. There is a guide for creating pseudoconsoles which explains the normal way to do this on windows.
So why didn't I just do that so that this worked properly? Well, I tried, but I couldn't figure out how to do it. You see, this is my first ever VBA project, and perhaps a more experienced VBA dev would be able to make this work, but I couldn't figure it out.
I know exactly what sequence of system calls are required, and I know what values to give them. The problem is just that these system calls have a more complicated set of arguments and I don't really know VBA well enough to get all the right pointers to these arguments. In the end I gave up, and just went with the thing that kinda worked already.
The other effect this had was that I couldn't escape the default config that programs use when they don't think they are connected to a terminal. In particular: bash echos the characters it receives by default. The problem this causes for me is that Word is also adding the same characters to the document, so every letter typed appears twice. This is something that you can normally configure by setting a flag in the virtual terminal device. Since I had given up on getting that working, instead I had to workaround this. So when bash is running, my terminal emulator deletes each character that Word adds to the document, so that only bash's echoed character remains.