My Weblog
27 05 2004

Thu, 27 May 2004

Scroll Wheel Hack for Text-Based Apps
Most mice these days have one of those scroll wheels as the middle button. Many graphical applications can use the scroll wheel to scroll various on-screen objects, such as list boxes and text boxes. I was wondering if it were possible to make text-based applications recognize the scroll wheel and scroll appropriately. I found some web sites that focused mainly on getting X to recognize the wheel, and a few that had info on configuring graphical apps to scroll on wheel clicks. The few pages that had any info on text-based apps provided a solution that mapped the wheel clicks to PageUp, PageDown, Up, Down, etc. While this works in many applications, it doesn't allow for the wheel to scroll by different amounts based on context (i.e. 1/2 page in less, 5 lines in vim, etc). So, I played with my .Xdefaults file a bit and came up with the following solution:

Instead of forcing the wheel clicks to map to PageUp or PageDown, why not map the clicks to unused escape sequences? This would effectively create two keys (or more if you want to use modifier keys with the wheel) that could then be mapped on a per-application basis. Here's the relevant section from my .Xdefaults file:


XTerm*vt100.translations: #override\n\
        Meta,: string("0x9b") string("[25;3~")\n\
        Meta,: string("0x9b") string("[26;3~")\n\
        Shift,: string("0x9b") string("[25;2~")\n\
        Shift,: string("0x9b") string("[26;2~")\n\
        Ctrl,: string("0x9b") string("[25;5~")\n\
        Ctrl,: string("0x9b") string("[26;5~")\n\
        ,: string("0x9b") string("[25~")\n\
        ,: string("0x9b") string("[26~")\n\

Here, I map button 4 (scroll up) to "^[[25~" and button 5 (scroll down) to "^[[26~" (the 'string("0x9b")' part expands to the escape character, or Ctrl-[ ). The other escape sequences are similar to what you would get if you held Ctrl, Shift, or Meta down while pressing a function key.

Once the above translations have been put into the .Xdefaults file and loaded (either by restarting X or running 'xrdb -merge .Xdefaults'), you can then configure text-based applications to recognize the wheel using their native key binding functions. For example, I put the following lines into my .zshrc to configure zsh to scroll through command history on wheel clicks:


bindkey "\233[25~"     up-line-or-history
bindkey "\233[26~"     down-line-or-history


Then, I configured less to scrolll 1/2 page on just a wheel click, a full page on shift+wheel click, and one line on ctrl + wheel click by putting this in my .lesskey and running lesskey:



posted at: 22:14 | path: /computers/linux | permanent link to this entry