iTerm and the Find pasteboard
Here’s another cool iTerm 2 trick: you can directly affect the system-wide Find pasteboard using escape codes.
The reason I got excited about this is that I’m used to having any search I run in one place (with ⌘F) automatically populate in other apps via the universal find pasteboard. The most notable time that this doesn’t work is when the search I was running was on the command line using grep
, ag
, or the like. Obviously, right? But what if a grep
could set the search field in other apps?
The iTerm Escape Code
Among the many special escape codes that iTerm recognizes is the CopyToClipboard
command. This command takes any text output after it, up to an EndCopy
command, and applies it to the clipboard. You can use a named clipboard to affect the rule, find, or font clipboards (blank to affect general clipboard). In this case we’re targeting the “find” clipboard, so the command is ^[]1337;CopyToClipboard=find^G
.
The Function (Fish)
So here’s my solution (for now). It’s not perfect as I can’t suppress the output and still have it work, so it just fades it to black before it outputs the text destined for the clipboard. This example is for ag
(silver searcher) in my Fish shell:
# Defined in ~/.config/fish/functions/ag.fish @ line 1
function ag -d "Silver Surfer defaults, smart case, ignore VCS"
printf '%sFind: \033]1337;CopyToClipboard=find\a%s\033]1337;EndCopy\a%s\n' \
(set_color -d black) \
"$argv[1]" \
(set_color normal)
command ag -SU $argv
end
(I did the same for ack
, but got tripped up when I tried to do it for grep
. It caused errors with RVM that I wasn’t able to track down. That’s ok, I rarely use grep directly.)
Because the meat of this is just a printf/echo command with the escape sequence, this is easily adapted to other shells (see below for a bash/zsh version).
It simply takes the first argument from the command line and echos it through iTerm’s “CopyToClipboard” command, then runs the utility itself, in this case ag
, using command
to skip any functions or aliases of the same name (like this current one, for example).
Now if I run ag pandoc
in a folder, “pandoc” shows up in my search field in iTerm so I can quickly ⌘G through the results, and when I switch over to my editor, it shows up there as soon as I hit ⌘F. Slick.
From the Top, With Bash Feeling
Here’s a Bash/Zsh version if you need it:
function ag() {
local BLACK="\033[30m"
local RESET="\033[m"
echo -e "${BLACK}Find: \033]1337;CopyToClipboard=find\a$1\033]1337;EndCopy\a${RESET}\n"
command ag -SU $@
}