The hovertext for Friday’s xkcd Borrow Your Laptop asks for scrolling mapped to undo and redo. How hard can it be? There’s more than one way to do this, but the other ways are boring. What if we’re using a program that doesn’t allow rebinding keys or buttons?
First we need to grab the scroll events. To avoid too much mischief, we’ll only bind to scroll events with the control key down. XGrabButton sure does take a lot of arguments, but only the first few are interesting.
This includes enough of an event loop to see that it’s working. Either undo or redo will be printed for each click of the wheel. Not exciting yet, but enough to see the code is working.
Now we need a function to send input back to the X server. Instead of printing undo on the screen, we want to make it happen. The usual way is to use XSendEvent, but many applications reject synthetic events as insecure. Fortunately, there’s a workaround using the XTest extension. In fact, it’s even less code to use XTest than XSendEvent. I have no idea why this is considered secure, though.
Because we have the control key held down, we need to fake lift it, or it’ll look like we’re sending control-u and control-r.
Testing this confirms it works, as a stream of u’s and r’s appear in my xterm, but they’re not being printed as output. They’re actually echoed input. This can be confirmed by moving the cursor over a different xterm and scrolling. Now the letters appear in that window.
Now comes the fun part. Different applications have different hotkeys for undo and redo, so we need to send different keystrokes to each. It’s only a very tiny function to read the window name (and crudely assume that’s the application).
Adapt the undo function accordingly.
If we’re running Firefox, undo is control-z and redo is shift-control-z. We already have control down, so just a matter of pressing shift or not, and then z. For vim, undo is plain u, no control. But redo is control-r. A little of this, a little of that. And for anything else, like the shell, we just send up and down keys and hope that works.
cc -Wall -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -lXtst timescroll.c
The xbindkeys and xvkbd programs may also be interesting.