CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-readline

GNU readline support for Python on platforms without readline

Pending
Overview
Eval results
Files

line-editing.mddocs/

Line Editing

Functions for accessing and manipulating the current line buffer, enabling custom editing behavior and text insertion capabilities. These functions provide direct access to the readline line buffer during interactive input.

Capabilities

Line Buffer Access

Functions for examining the current state of the readline input buffer, useful for custom completion and editing functions.

def get_line_buffer():
    """
    Return the current contents of the line buffer.
    
    Returns:
    str: Current line buffer contents
    """

Usage Example:

import readline

def smart_completer(text, state):
    # Access the full line being edited
    line_buffer = readline.get_line_buffer()
    
    # Provide context-aware completion based on full line
    if line_buffer.startswith('cd '):
        # Directory completion for cd command
        import os
        import glob
        matches = glob.glob(text + '*')
        directories = [match for match in matches if os.path.isdir(match)]
        return directories[state] if state < len(directories) else None
    elif line_buffer.startswith('python '):
        # Python file completion
        matches = glob.glob(text + '*.py')
        return matches[state] if state < len(matches) else None
    
    return None

readline.set_completer(smart_completer)

Text Insertion

Functions for programmatically inserting text into the current command line, useful for custom editing commands and macros.

def insert_text(string):
    """
    Insert text into the command line.
    
    Parameters:
    - string (str): Text to insert at current cursor position
    
    Returns:
    None
    """

Usage Example:

import readline

def insert_common_commands():
    """Example function to insert commonly used text"""
    # This could be bound to a key combination
    common_commands = [
        "ls -la",
        "cd ~/",
        "git status",
        "python -m",
    ]
    
    # In practice, you'd select based on context or user choice
    readline.insert_text("ls -la")

# Insert text during completion or editing
def custom_pre_input_hook():
    # Insert default text when starting a new line
    current_line = readline.get_line_buffer()
    if not current_line:  # Empty line
        readline.insert_text("$ ")  # Add prompt-like prefix

readline.set_pre_input_hook(custom_pre_input_hook)

Display Control

Functions for controlling how the current line is displayed, useful when programmatically modifying the line buffer.

def redisplay():
    """
    Change what's displayed on screen to reflect current line buffer contents.
    
    Returns:
    None
    """

Usage Example:

import readline

def modify_and_refresh():
    """Example of modifying line buffer and refreshing display"""
    # Get current content
    current = readline.get_line_buffer()
    
    # Clear current line (this would normally be done differently)
    # This is just for demonstration
    if current:
        # Insert modified text
        readline.insert_text(" --verbose")
        
        # Force display update
        readline.redisplay()

# Practical usage in a completion display hook
def custom_display_hook(substitution, matches, longest_match_length):
    """Custom completion display with line buffer modification"""
    print(f"\nAvailable completions ({len(matches)}):")
    for i, match in enumerate(matches[:10]):  # Show first 10
        print(f"  {i+1}. {match}")
    
    if len(matches) > 10:
        print(f"  ... and {len(matches) - 10} more")
    
    # Refresh the input line after our custom display
    readline.redisplay()

readline.set_completion_display_matches_hook(custom_display_hook)

Advanced Line Editing Patterns

Context-Aware Editing

import readline

def context_aware_editor():
    """Example of context-aware line editing"""
    line = readline.get_line_buffer()
    
    # Auto-complete file paths
    if line.endswith(' '):
        last_word = line.split()[-1] if line.split() else ""
        if last_word.startswith('/'):
            # Insert common path completion
            readline.insert_text("home/user/")
    
    # Auto-insert common parameters
    if line.strip().endswith('git'):
        readline.insert_text(" status")
        readline.redisplay()

# Use with pre-input hook for automatic editing
readline.set_pre_input_hook(context_aware_editor)

Command Line Macros

import readline

class CommandMacros:
    def __init__(self):
        self.macros = {
            'll': 'ls -la --color=auto',
            'la': 'ls -A',
            'l': 'ls -CF',
            'grep': 'grep --color=auto',
        }
    
    def expand_macro(self):
        """Expand macros in the current line"""
        line = readline.get_line_buffer()
        words = line.split()
        
        if words and words[0] in self.macros:
            # Replace the macro with its expansion
            expanded = self.macros[words[0]]
            new_line = expanded + ' ' + ' '.join(words[1:])
            
            # Clear current line and insert expanded version
            readline.insert_text('\b' * len(line))  # Backspace to clear
            readline.insert_text(new_line)
            readline.redisplay()

# Usage would require key binding setup through parse_and_bind

Install with Tessl CLI

npx tessl i tessl/pypi-readline

docs

completion.md

configuration.md

history.md

hooks.md

index.md

line-editing.md

tile.json