Skip to content

Instantly share code, notes, and snippets.

@notdaniel
Last active February 27, 2025 01:37
Show Gist options
  • Save notdaniel/9c24f2eeee6fdabc4cd530ff733c868d to your computer and use it in GitHub Desktop.
Save notdaniel/9c24f2eeee6fdabc4cd530ff733c868d to your computer and use it in GitHub Desktop.
removes excess indentation from clipboard text on macos
#!/usr/bin/python3
import shutil
import subprocess
import textwrap
def check_commands():
"""Ensure `pbcopy` and `pbpaste` are available."""
if not all(map(shutil.which, ("pbcopy", "pbpaste"))):
raise SystemExit("could not find pbcopy/pbpaste. are you on a mac?")
return True
def load_clipboard():
"""Read the clipboard contents."""
try:
p = subprocess.run(["pbpaste"], stdout=subprocess.PIPE, text=True, check=True)
return p.stdout
except subprocess.CalledProcessError:
raise SystemExit("error: failed to read from clipboard")
def to_clipboard(text):
"""Write text to the clipboard."""
try:
p = subprocess.run(["pbcopy"], input=text, text=True, check=True)
return p.returncode == 0
except subprocess.CalledProcessError:
raise SystemExit("error: failed to write to clipboard")
def dedent_clipboard():
"""Dedent the clipboard contents."""
text = load_clipboard()
if text:
dedented = textwrap.dedent(text).strip()
if dedented == text: # no dedenting needed, don't write to clipboard
return True
return to_clipboard(dedented)
if __name__ == "__main__":
check_commands()
dedent_clipboard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment