or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-python-editor

Programmatically open an editor, capture the result.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-editor@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-python-editor@1.0.0

index.mddocs/

Python Editor

A Python library for programmatically interfacing with system text editors. The editor module provides a simple API that allows developers to open text editors in subprocesses, capture user input, and handle the results with automatic editor detection and cross-platform compatibility.

Package Information

  • Package Name: python-editor
  • Package Type: pypi
  • Language: Python
  • Installation: pip install python-editor

Core Imports

import editor

Basic Usage

import editor

# Open editor with initial content
commit_msg = editor.edit(contents=b"# Enter commit message here")
print(commit_msg.decode())

# Edit an existing file
editor.edit(filename="README.txt")

# Use TTY for piped programs
editor.edit(contents=b"Initial content", use_tty=True)

# Create temporary file with specific suffix
content = editor.edit(contents=b"# Comments", suffix='.py')

Architecture

The library follows a simple three-stage process:

  1. Editor Detection: Finds the appropriate editor using environment variables ($VISUAL, $EDITOR) or system defaults (editor, vim, emacs, nano)
  2. File Preparation: Creates temporary files when needed and pre-populates content
  3. Subprocess Invocation: Launches the editor with platform-appropriate arguments and handles TTY redirection for piped programs

The design prioritizes simplicity and cross-platform compatibility, automatically handling editor-specific command-line arguments and TTY management.

Capabilities

Text Editor Invocation

The primary functionality for opening text editors and capturing results.

def edit(filename=None, contents=None, use_tty=None, suffix=''):
    """
    Open a text editor and capture the result.

    Parameters:
    - filename (str, optional): Path to file to edit. If None, creates temporary file
    - contents (bytes/str, optional): Initial contents to populate in editor
    - use_tty (bool, optional): Whether to use TTY for output. Auto-detected if None
    - suffix (str, optional): File suffix for temporary files when filename is None

    Returns:
    bytes: Contents of the file after editing

    Raises:
    EditorError: If no viable editor can be found on the system
    """

Editor Detection

Discovers the preferred text editor from environment variables or system defaults.

def get_editor():
    """
    Get the preferred editor from environment or system defaults.

    Returns:
    str: Path to editor executable

    Raises:
    EditorError: If no viable editor can be found on the system
    """

Utility Functions

Advanced utility functions for customizing editor behavior.

def get_default_editors():
    """
    Get the list of default editors to search for.

    Returns:
    list: List of editor names in priority order ['editor', 'vim', 'emacs', 'nano']
    """

def get_editor_args(editor):
    """
    Get command-line arguments for specific editors.

    Parameters:
    - editor (str): Editor name or path

    Returns:
    list: List of command-line arguments appropriate for the editor
    """

Module Constants

__version__: str
    # Version string of the python-editor package

__all__: list
    # Exported API: ['edit', 'get_editor', 'EditorError']

Error Handling

class EditorError(RuntimeError):
    """
    Exception raised when editor operations fail.
    
    Typically raised when no viable editor can be found on the system.
    """

Editor Detection Logic

The library uses the following priority order to find an editor:

  1. Environment Variables: Checks $VISUAL then $EDITOR
  2. System Defaults: Searches for common editors in PATH:
    • editor (system default)
    • vim
    • emacs
    • nano

Platform Support

  • Cross-platform: Works on Windows, macOS, and Linux
  • TTY Handling:
    • Windows uses CON: for TTY
    • Unix/Linux uses /dev/tty
  • Editor-specific Arguments: Automatically applies appropriate command-line arguments:
    • vim/gvim: -f -o (foreground, open in tabs)
    • emacs: -nw (no window system)
    • gedit: -w --new-window (wait, new window)
    • nano: -R (restricted mode)

Usage Examples

Basic Text Editing

import editor

# Simple text editing
content = editor.edit(contents="Initial text")
print("Edited content:", content.decode())

File Editing

import editor

# Edit existing file in place
editor.edit(filename="/path/to/file.txt")

# Edit file with initial content (overwrites existing)
editor.edit(filename="/path/to/file.txt", contents="New content")

Temporary File Creation

import editor

# Create temporary Python file
code = editor.edit(suffix='.py', contents='# Write your Python code here')
print("Python code:", code.decode())

# Create temporary file with no initial content
notes = editor.edit(suffix='.md')
print("Notes:", notes.decode())

TTY Usage for Piped Programs

import editor

# When stdout is piped, use TTY for interactive editing
content = editor.edit(contents="Edit this text", use_tty=True)

Advanced Usage

import editor

# Check available default editors
default_editors = editor.get_default_editors()
print("Default editors:", default_editors)

# Get editor-specific arguments
vim_args = editor.get_editor_args('vim')
print("Vim arguments:", vim_args)  # ['-f', '-o']

# Check version
print("Library version:", editor.__version__)

Error Handling

import editor

try:
    content = editor.edit(contents="Some text")
    print("Success:", content.decode())
except editor.EditorError as e:
    print("Editor error:", e)
    print("Please set your $EDITOR environment variable")