CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-thefuck

Magnificent app which corrects your previous console command

Overview
Eval results
Files

user-interface.mddocs/

User Interface and Interaction

Interactive command selection, keyboard input handling, and user confirmation interfaces for selecting and executing corrections. The UI system provides cross-platform terminal interaction with intuitive navigation and selection capabilities.

Capabilities

Interactive Command Selection

Core class for managing command selection with keyboard navigation.

class CommandSelector:
    """
    Interactive command selection with navigation.
    
    Provides navigation through multiple command corrections with
    keyboard controls and change event handling.
    """
    
    def __init__(self, commands):
        """
        Initialize command selector.
        
        Parameters:
        - commands (SortedCorrectedCommandsSequence): Available corrections
        """
    
    def next(self):
        """
        Move to next command in the list.
        
        Wraps around to first command when reaching the end.
        Triggers change callback with new selection.
        """
    
    def previous(self):
        """
        Move to previous command in the list.
        
        Wraps around to last command when at the beginning.
        Triggers change callback with new selection.
        """
    
    @property
    def value(self):
        """
        Get currently selected command.
        
        Returns:
        CorrectedCommand: Currently selected correction
        """
    
    def on_change(self, fn):
        """
        Register callback for selection changes.
        
        Parameters:
        - fn (callable): Function to call when selection changes
        
        The callback receives the new selected command as parameter.
        """

Input and Action Processing

Functions for handling keyboard input and converting to user actions.

def getch():
    """
    Cross-platform single character input without echo.
    
    Returns:
    str: Single character from keyboard input
    
    Raises:
    KeyboardInterrupt: When Ctrl+C is pressed
    
    Platform-specific implementation:
    - Windows: Uses msvcrt.getch()
    - Unix/Linux/macOS: Uses termios for raw input
    """

def read_actions():
    """
    Generator yielding actions for pressed keys.
    
    Yields:
    int: Action constants (SELECT, ABORT, PREVIOUS, NEXT)
    
    Key mappings:
    - Enter/Return: SELECT
    - Ctrl+C: ABORT
    - Up Arrow: PREVIOUS
    - Down Arrow: NEXT
    """

Main Selection Interface Function

High-level function for complete command selection workflow.

def select_command(corrected_commands, settings):
    """
    Interactive command selection interface.
    
    Parameters:
    - corrected_commands (SortedCorrectedCommandsSequence): Available corrections
    - settings (Settings): Application settings
    
    Returns:
    CorrectedCommand or None: Selected command or None if aborted
    
    Behavior:
    - Returns first command immediately if require_confirmation=False
    - Returns None if no corrections available
    - Provides interactive selection if require_confirmation=True
    - Handles user abort (Ctrl+C) gracefully
    
    Interactive controls:
    - Enter: Select current command
    - Up/Down arrows: Navigate between options
    - Ctrl+C: Abort selection
    """

Action Constants

User action constants for keyboard input interpretation.

SELECT = 0
    """Action constant for selecting current command (Enter key)."""

ABORT = 1
    """Action constant for aborting selection (Ctrl+C)."""

PREVIOUS = 2
    """Action constant for moving to previous command (Up arrow)."""

NEXT = 3
    """Action constant for moving to next command (Down arrow)."""

Usage Examples

Basic Command Selection

from thefuck.ui import select_command
from thefuck.corrector import get_corrected_commands
from thefuck.types import Command

# Setup (assuming settings and user_dir are available)
command = Command("git pussh origin main", "", "git: 'pussh' is not a git command")
corrections = get_corrected_commands(command, user_dir, settings)

# Interactive selection
selected = select_command(corrections, settings)

if selected:
    print(f"User selected: {selected.script}")
else:
    print("User aborted selection")

Manual Command Selector Usage

from thefuck.ui import CommandSelector
from thefuck.types import CorrectedCommand

# Create some example corrections
corrections = [
    CorrectedCommand("git push origin main", None, 1000),
    CorrectedCommand("git push origin master", None, 1100),
    CorrectedCommand("git push --set-upstream origin main", None, 1200)
]

# Create selector
selector = CommandSelector(corrections)

# Set up change handler
def on_selection_change(command):
    print(f"Now selected: {command.script}")

selector.on_change(on_selection_change)

# Navigate programmatically
print(f"Initial: {selector.value.script}")
selector.next()
print(f"After next: {selector.value.script}")
selector.previous()
print(f"After previous: {selector.value.script}")

Custom Input Processing

from thefuck.ui import read_actions, SELECT, ABORT, PREVIOUS, NEXT

# Process user input manually
print("Use arrow keys to navigate, Enter to select, Ctrl+C to abort:")

for action in read_actions():
    if action == SELECT:
        print("User selected current option")
        break
    elif action == ABORT:
        print("User aborted")
        break
    elif action == PREVIOUS:
        print("User wants previous option")
    elif action == NEXT:
        print("User wants next option")

Settings-Aware Selection

from thefuck.ui import select_command
from thefuck.types import Settings

# Create settings that skip confirmation
settings = Settings({
    'require_confirmation': False,
    'no_colors': False
})

# This will return first correction immediately without user interaction
selected = select_command(corrections, settings)
print(f"Auto-selected: {selected.script}")

# Enable confirmation for interactive selection
interactive_settings = settings.update(require_confirmation=True)
selected = select_command(corrections, interactive_settings)

Platform Compatibility

The UI system handles cross-platform differences transparently:

Windows Support

  • Uses msvcrt.getch() for character input
  • Handles Windows-specific key codes
  • Supports standard Windows terminal behavior

Unix/Linux/macOS Support

  • Uses termios and tty modules for raw input
  • Handles ANSI escape sequences for arrow keys
  • Maintains terminal state properly
  • Supports various terminal emulators

Common Features

  • Ctrl+C handling for graceful interruption
  • Arrow key navigation (↑/↓)
  • Enter key selection
  • No echo during input
  • Proper cleanup of terminal state

Display Integration

The UI system integrates with the logging system for display:

Visual Feedback

  • Shows current selection highlighting
  • Displays navigation instructions
  • Provides confirmation prompts
  • Shows error messages for no corrections

Color Support

  • Respects no_colors setting
  • Uses colored output when available
  • Falls back gracefully on non-color terminals

Error Handling

The UI system handles various error conditions:

  • No corrections available: Shows appropriate message and returns None
  • Keyboard interrupt: Catches Ctrl+C and returns None gracefully
  • Terminal errors: Handles terminal state restoration on errors
  • Invalid input: Ignores unrecognized keystrokes
  • Empty command lists: Handles gracefully without crashing

Accessibility

The interface provides good accessibility:

  • Keyboard-only navigation: No mouse required
  • Clear feedback: Visual and textual confirmation of actions
  • Standard key mappings: Uses common terminal navigation patterns
  • Escape options: Always provides way to abort
  • Simple interface: Minimal learning curve for users

Install with Tessl CLI

npx tessl i tessl/pypi-thefuck

docs

configuration.md

core-application.md

data-types.md

index.md

rule-development.md

rule-system.md

shell-integration.md

user-interface.md

utilities.md

tile.json