10 of 15
added 73 characters in body
  • 209.6k
  • 41
  • 368
  • 819

Bash, 67 55 50 35 bytes

:()(read -p›4$[i^=2]m›J›?9h -sn6

The code contains three occurrences of the CSI byte (0x9b). Most browsers will display them using the Windows-1252 encoding (small right angle bracket).

The code defines a function named :, which paints the entire terminal green or black on left click, then calls itself. It requires xterm (or equivalent) and the ISO-8859-1 encoding (or similar).

Thanks to @ais523 for suggesting xterm, which saves 4 bytes!

How it works

:(...) creates a function named : that executes ....

The read command does the actual magic.

  • -p specifies an input prompt, which is printed to STDOUT.

    $[i^=2] is an arithmetic expansion which XORs the variable i with 2. i may initially be unset; when this occurs, it will be treated as 0.

    All parts of the prompt have special meanings to the terminal emulator.

    • ›4$[i^=2]m sets the background color to green if i = 2 and black if i = 0.

    • ›J clears the terminal from the current cursor position to the end, painting it in the selected background color.

    • ›?9h captures the mouse in supported terminals. Each click will send six characters to the terminal, namely ←[Mbxy, where represents the ESC byte (0x1b). ←[ indicates an escape sequence, M the mouse, b the button (0x20 + the button number), x the x coordinate of the click (0x20 + coordinate), and y the y coordinate.

    • -sn6 makes read silent (the from mouse input won't be echoed to the terminal) and stops after reading exactly 6 bytes. It saves the input in the REPLY variable, but we're not interested in the output it produces.

Finally, once read finishes (after exactly one mouse click), : recursively call itself, entering an infinite loop.

Creation and invocation

$ printf ':()(read -p\x9b4$[i^=2]m\x9bJ\x9b?9h -sn6\n:)\n:' > checkbox.sh
$ xxd -g 1 checkbox.sh
0000000: 3a 28 29 28 72 65 61 64 20 2d 70 9b 34 24 5b 69  :()(read -p.4$[i
0000010: 5e 3d 32 5d 6d 9b 4a 9b 3f 39 68 20 2d 73 6e 36  ^=2]m.J.?9h -sn6
0000020: 0a 3a 29 0a 3a                                   .:).:
$ LANG=en_US xterm -e bash checkbox.sh



Not quite as ugly as in real life as the VirtualBox screencast makes it look. Here are two high quality screenshots from my desktop computer: checked | unchecked

  • 209.6k
  • 41
  • 368
  • 819