Edit

Automate and integrate Edit workflows to streamline your editing process

Edit is a community skill for performing structured text and code editing operations, covering find-and-replace patterns, AST-based code transformations, multi-file refactoring, diff generation, and batch editing workflows for codebase maintenance.

What Is This?

Overview

Edit provides patterns for programmatically modifying text and source code files. It covers find-and-replace that applies regex and literal string substitutions with preview and confirmation, AST-based transformations that modify code structure by parsing the syntax tree rather than manipulating raw text, multi-file refactoring that applies consistent changes across a codebase with dependency tracking, diff generation that produces unified diffs showing before and after states for review, and batch workflows that chain multiple edit operations with rollback support. The skill enables developers to perform reliable large-scale code modifications.

Who Should Use This

This skill serves developers performing codebase-wide refactoring, toolchain engineers building code modification scripts, and teams maintaining large codebases that need systematic editing capabilities.

Why Use It?

Problems It Solves

Manual find-and-replace misses edge cases like partial matches within larger identifiers. Text-based code transformations break when formatting changes or comments appear in unexpected positions. Multi-file edits without preview create hard-to-review changes that may introduce bugs. Batch edits without rollback leave the codebase in an inconsistent state when errors occur midway.

Core Highlights

Pattern matcher applies regex and literal substitutions with scope control. AST transformer modifies code structure through parsed syntax tree manipulation. Multi-file editor applies changes across files with dependency awareness. Diff previewer generates unified diffs for review before applying changes.

How to Use It?

Basic Usage

import re
from pathlib import Path
from dataclasses\
  import dataclass

@dataclass
class EditOp:
  pattern: str
  replacement: str
  is_regex: bool = False

class FileEditor:
  def __init__(
    self,
    filepath: str
  ):
    self.path = Path(
      filepath)
    self.original =\
      self.path\
        .read_text()
    self.content =\
      self.original

  def apply(
    self,
    op: EditOp
  ) -> int:
    if op.is_regex:
      new, count =\
        re.subn(
          op.pattern,
          op.replacement,
          self.content)
    else:
      count = self\
        .content.count(
          op.pattern)
      new = self\
        .content.replace(
          op.pattern,
          op.replacement)
    self.content = new
    return count

  def diff(self) -> str:
    import difflib
    return '\n'.join(
      difflib.unified_diff(
        self.original\
          .splitlines(),
        self.content\
          .splitlines(),
        lineterm=''))

  def save(self):
    self.path\
      .write_text(
        self.content)

Real-World Examples

class BatchEditor:
  def __init__(self):
    self.editors = {}
    self.log = []

  def add_files(
    self,
    glob_pattern: str
  ):
    for path in Path('.')\
        .glob(glob_pattern):
      self.editors[
        str(path)] =\
          FileEditor(
            str(path))

  def apply_all(
    self,
    op: EditOp
  ) -> dict:
    results = {}
    for path, editor\
        in self.editors\
          .items():
      count = editor\
        .apply(op)
      if count > 0:
        results[path]\
          = count
        self.log.append({
          'file': path,
          'op': op.pattern,
          'count': count})
    return results

  def preview(self):
    for path, editor\
        in self.editors\
          .items():
      d = editor.diff()
      if d:
        print(f'--- {path}')
        print(d)

Advanced Tips

Use word boundary anchors in regex patterns to avoid matching substrings within larger identifiers when renaming variables or functions. Generate and review diffs before saving changes to catch unintended modifications in files you did not expect to change. Implement a backup mechanism that saves original file contents before applying batch edits so changes can be reverted if issues are discovered after saving.

When to Use It?

Use Cases

Rename a function across an entire codebase with regex word boundary matching to avoid partial hits. Apply a consistent code pattern change across multiple files with diff preview before committing. Build a migration script that updates API call patterns from an old version to a new one.

Related Topics

Text editing, code refactoring, find and replace, AST transformation, batch editing, and diff generation.

Important Notes

Requirements

Python standard library for regex and file operations. Difflib module for generating unified diff output. Version control for safe rollback of batch changes that span multiple files.

Usage Recommendations

Do: preview diffs before saving to catch unintended changes in unexpected files. Use regex word boundaries for identifier renaming to prevent partial matches. Commit current work before running batch edits so version control provides a rollback point.

Don't: apply regex replacements without testing the pattern on a sample first since complex patterns may have unexpected matches. Edit generated or vendored files that will be overwritten on the next build or dependency update. Chain many edit operations without intermediate review which makes it difficult to identify which operation introduced a problem.

Limitations

Text-based editing cannot distinguish between syntactically identical patterns used in different semantic contexts such as a variable name that matches a string literal. Regex patterns do not understand code structure so transformations that need scope awareness require AST-based tools. Large-scale batch edits may produce merge conflicts with other in-progress branches.