Capture Mouse Events in the Terminal using Ruby

Abstract: Enable mouse tracking in Ruby terminals using ANSI escape sequences and raw input mode to parse coordinate data from the binary stream.

Created: 2026-08-19 by
Capture mouse events in the terminal using Ruby by enabling mouse tracking via ANSI escape sequences. The process involves sending specific control codes to the terminal emulator, reading raw input from standard input without line buffering, and parsing the binary data stream generated by mouse movements and clicks.

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 the IO#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, using RubyInstaller 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More