I spend a fair amount of time on Stack Overflow, following interesting topics and answering the occasional question. Writing answers on Stack Overflow usually means writing and testing code, using Emacs and Mac Terminal. When finished, copy-paste code into the form on Stack Overflow and apply formatting using Markdown.
Since I normally use Emacs in terminal mode (
emacs -nw), I have problems with the copy-paste: Marking lines with the mouse and copying them puts lots of spaces at the end of each line. It’s a well known problem with screened terminal applications (using ncurses or similar), copying gets you the entire physical line on screen, whitespace and all.
What I needed was a way to ltrim() each line in the pasteboard (Mac:ish for clipboard) after copying. It turns out this was easy with the help of a few utilities:
- The Mac OSX commands pbcopy and pbpaste handle copy and paste from the commandline.
- BetterTouchTool is a great (free) tool for custom keyboard shortcuts and gestures.
- A small bash script to do the actual trimming, I call it
1 2 3 4 5 6
Save pbtrim somewhere on your
$PATH and make it executable.
Open BetterTouchTool. Create a new keyboard shortcut for application Terminal. I use
Cmd-Shift-C. Make it Trigger Other Keyboard Shortcut
Cmd-C. Now you have an alternate shortcut for the copy command. Next Attach Additional Action, choose Controlling Other Applications then Execute Terminal Command:
Cmd-Shift-C will first trigger a normal copy, then run
pbtrim to remove terminating whitespace. Ready to paste into Stackoverflow!