Gap buffers
Fixing two typos in “helo_wrld”, slot by slot, shows how a hole kept at the cursor makes typing cheap, and what it costs to move that hole.
In 30 seconds
Text in a plain array is slow to edit: typing one character in the middle shifts everything after it.
A gap buffer is an array with its spare room, the gap, kept at the cursor. Typing drops a character into the gap; deleting widens the gap. Nothing else moves.
Editing somewhere else means moving the gap there first, one copy per character crossed. Since people type in bursts at one spot, that cost is paid rarely, which is why text editors such as Emacs use it.
Gap buffers, step by step
Real gaps are thousands of slots wide. Other editors use different structures, such as ropes or piece tables, which handle huge files and many cursors better.
- Step 1: The slow way: a plain array. Keep a line of text in an ordinary array and every keystroke in the middle is expensive. To type the missing l in “helo_wrld”, the six characters after it must each shift one slot right first. In a long file, that is thousands of moves per key.
- Step 2: Put the gap at the cursor. A gap buffer is the same array with the spare room moved to where the cursor is. The text before the cursor sits at the front, the text after it at the back, and the unused slots, the gap, lie in between. The gap is not part of the text; the screen never shows it.
- Step 3: Typing fills the gap. Typing l writes it into the first slot of the gap and moves gap_start up by one. No other character is touched. Backspace is just as cheap: move gap_start down by one and the erased slot rejoins the gap.
- Step 4: Edit elsewhere: move the gap. The next fix is three characters further on, before “rld”. The gap must be there first, so the characters in between, o, _ and w, are copied from the far side of the gap to the near side. Three characters crossed, three moves. Editors usually do this only when you actually edit at the new spot.
- Step 5: Type again for free. With the gap in place, typing is free again: o lands in slot 7 and the text reads “hello_world”. People type in bursts at one spot, so the usual keystroke costs nothing extra and the gap is moved only now and then.
- Step 6: A long jump costs more. The cost of moving the gap is the distance travelled. Editing at the very start of the line means all eight characters before the cursor must hop to the other side: eight moves. Jump from the end of a huge file to its top and type, and the editor copies everything in between.
- Step 7: Why editors like it. A gap buffer is two numbers and one array, yet it makes the commonest action, typing where you already are, as cheap as possible. GNU Emacs stores each buffer this way. When the gap fills up, the editor copies the text into a bigger array with a fresh gap.
Try it yourself
Learn this first
Spotted a mistake on this page?