libtermkey - overview

This library allows easy processing of keyboard entry from terminal-based programs. It handles all the necessary logic to recognise special keys, UTF-8 combining, and so on, with a simple interface.

The library itself comes with a complete collection of manpages that explain the full detail of the functions used. A brief overview will be given here.

Consider the following demonstration program that just prints pressed keys:

#include <stdio.h>

#include "termkey.h"

int main(int argc, char *argv[]) {
  char buffer[50];
  TermKey *tk = termkey_new(0, 0);

  if(!tk) {
    fprintf(stderr, "Cannot allocate termkey instance\n");

  TermKeyResult ret;
  TermKeyKey key;

  while((ret = termkey_waitkey(tk, &key)) != TERMKEY_RES_EOF) {
    termkey_strfkey(tk, buffer, sizeof buffer, &key, TERMKEY_FORMAT_VIM);
    printf("You pressed key %s\n", buffer);

    if(key.type == TERMKEY_TYPE_UNICODE &&
       key.modifiers & TERMKEY_KEYMOD_CTRL &&
       (key.code.codepoint == 'C' || key.code.codepoint == 'c'))


The four functions used here are:


TermKey *termkey_new(int fd, int flags);

Construct a new TermKey instance, to wrap the file descriptor given in fd, using the given flags. The default flags implied by 0 are usually sufficient for most purposes.


TermKeyResult termkey_waitkey(TermKey *tk, TermKeyKey *key);

Synchronously block on terminal input, and return as soon as a key is pressed. Details of the keypress will be put in the key structure provided. This structure is declared as:

typedef struct {
    TermKeyType type;
    union {
        long       codepoint; /* TERMKEY_TYPE_UNICODE  */
        int        number;    /* TERMKEY_TYPE_FUNCTION */
        TermKeySym sym;       /* TERMKEY_TYPE_KEYSYM   */
        char       mouse[4];  /* TERMKEY_TYPE_MOUSE
                                 opaque. see termkey_interpret_mouse */
    } code;
    int modifiers;
    char utf8[7];
} TermKeyKey;


size_t termkey_strfkey(TermKey *tk, char *buffer, size_t len,
                   TermKeyKey key, TermKeyFormat format);

Format a string buffer to contain a string description of the keypress. Similar in operation to snprintf() or strftime().


void termkey_destroy(TermKey *tk);

Frees the memory used by the TermKey instance, and restore the terminal back to its original state.