Enabling Mouse Tracking in the Terminal
Most modern terminal emulators support a feature called "mouse reporting" or "mouse tracking." To capture these events, you must first instruct your terminal to start sending mouse coordinates and button states as part of the input stream. This is achieved by writing specific ANSI escape sequences to the standard output. The most common mode for capturing detailed mouse events is SGR (Select Graphic Rendition) mode. You enable this by sending the sequence\e[?1006h to stdout. Conversely, to disable it later, send \e[?1006l. Some older terminals might require \e[?1000h for basic motion tracking, but 1006 provides the precise x and y coordinates along with the button state, which is essential for interactive applications like text editors or games.
It is crucial to understand that simply sending the code does not guarantee support. If the terminal does not support mouse reporting, it will ignore the sequence. However, assuming a standard environment like GNOME Terminal, iTerm2, or Windows Terminal, this step is usually sufficient.
Configuring Ruby Input Mode
By default, Ruby reads input line-by-line, waiting for the user to press Enter. This behavior blocks the ability to read individual keystrokes or mouse events as they occur. To capture real-time events, you must put the terminal into "raw" mode. In raw mode, the terminal driver stops processing special characters like backspace or enter, and disables canonical input processing. In Ruby, you can achieve this using theIO#tty? check and the stty command via system calls, or more portably, by using the curses library or external gems like io-console. For a pure standard library approach without heavy dependencies, you often need to manipulate the termios settings.
A common pattern involves saving the current terminal attributes, applying new attributes that disable echo and canonical mode, and then restoring them upon exit. This ensures that if your script crashes, the terminal returns to its normal state. Failure to restore these settings can leave your terminal in a broken state where no keys are interpreted correctly until the shell resets them.
Parsing the Mouse Event Stream
Once mouse tracking is enabled and input is in raw mode, every mouse click or movement generates a multi-byte sequence sent to stdin. The format depends on the mode you enabled. In SGR mode (1006), the sequence looks like \e[<button;x;y;M for a release or \e[<button;x;y;m for a press. Here, < represents the button number, x and y are the column and row coordinates, and M/m indicates the action.
You need to read from $stdin byte-by-byte or in small chunks. A robust parser checks for the escape character \e (ASCII 27). Upon finding it, it buffers subsequent bytes until it finds the closing M or m. Then, it splits the string by semicolons to extract the button, x, and y values.
For example, a left-click at column 10, row 5 would appear as \e[<0;10;5;M. Your Ruby code should convert these string numbers to integers for use in your application logic. It is also important to handle wheel events, which typically use higher button numbers (like 4 and 5) or specific modifiers.
Complete Implementation Example
Below is a simplified structure for a Ruby script that captures these events. Note that proper error handling and terminal restoration are omitted for brevity but are critical for production code.require 'io/console'
def main
# Enable SGR mouse mode
print "\e[?1006h"
begin
loop do
# Read one byte at a time
char = $stdin.getbyte
if char == 27 # Escape character
buffer = ""
loop do
c = $stdin.getbyte
buffer += c.chr
break if c == 109 || c == 77 # 'm' or 'M'
end
# Parse buffer: \e[<button;x;y;action
parts = buffer.split(';')
if parts.length >= 4
button = parts[1].to_i
x = parts[2].to_i
y = parts[3].to_i - 1 # Adjust for zero-indexing
puts "Click: Button #{button} at (#{x}, #{y})"
end
end
end
ensure
# Disable mouse mode
print "\e[?1006l"
end
end
main
This script listens indefinitely. When you run it, move your mouse over the terminal window and click. The coordinates and button states will be printed to the console. Remember that some terminals may require you to have focus on the terminal window for events to be captured.
If you encounter issues where Ruby throws errors about running the code, check your environment variables and ensure you are not mixing incompatible libraries. See Why does Ruby not let me run this even though it's correct? for troubleshooting runtime errors.
Troubleshooting Common Issues
One frequent problem is receiving no output at all. This usually means the terminal did not acknowledge the mouse tracking request. Verify that your terminal emulator supports it. Another issue is garbled output. This happens if the parser fails to synchronize with the escape sequence. Ensure you are reading raw bytes and not relying on line-based input methods. Additionally, consider that different operating systems may have slight variations in how they handle input streams. On Windows, usingRubyInstaller or Cygwin might require additional configuration to access low-level terminal controls. If you are developing cross-platform tools, abstracting the input layer behind an interface can help manage these differences.
Finally, always test your script in a controlled environment before deploying it to production systems. Unexpected behavior in headless servers or CI/CD pipelines is common when assuming terminal interactivity.
Frequently Asked Questions
Does this work on all terminal emulators?
No, only terminals that support ANSI mouse reporting will work. Most modern Linux terminals (GNOME, Konsole) and macOS terminals (iTerm2, Terminal.app) support it, but lightweight SSH clients or ancient emulators may not.
How do I detect scroll wheel events?
Scroll wheel events are typically reported as button presses with button numbers 4 (up) and 5 (down). You can parse these same sequences and react based on the button ID rather than just 0, 1, or 2 for standard clicks.
Can I capture mouse events over SSH?
Yes, provided both the local and remote terminal emulators support mouse reporting. You must enable it on the client side and ensure the server-side program sends the initialization codes to the remote stdout.
What happens if my script crashes without disabling mouse mode?
Your terminal will continue to send mouse coordinates as input instead of normal characters. This makes typing difficult or impossible until you manually reset the terminal settings using the stty sane command in a new shell.
Is there a gem that simplifies this process?
Yes, gems like termios or io-console provide safer wrappers for manipulating terminal attributes. While the manual approach works, these gems reduce boilerplate and help prevent common pitfalls in setting up raw input modes.