Filter Through Command in BBEdit

I’ve used BBEdit for a long time, but only recently started digging into the scripting side of it. If you’re willing to write your script against it’s scripting dictionary in AppleScript or JavaScript, you can do a lot, including attaching a script to every menu command in the app. You do however have to write a script and put it in the right place before you can use it. Sometimes I’d rather pipe my text through grep 'foo' | sort -u like you can on the command line, and have it format my text for me.

TextMate has exactly this command, so emulating that seemed like a good place to start:


I figured out that I could build most of what TextMate has as a BBEdit Text Filter:


Dr Drang had already done pretty much exactly the same thing, but I wanted my script to remember at least the last command I ran, which won’t work with his approach. To get that, I needed to make a proper AppleScript so that I could take advantage of persistent properties (which is a super useful thing AppleScript can do if they’re saved as an scpt file).

You can copy the script below into Script Editor and save it in script format to BBEdit’s Text Filters folder:

property default_command : "sort"

on RunFromBBEdit(_range)
	set shell_command to the text returned of (display dialog "Enter a shell command:" with title "Filter Through Command" default answer default_command)
	if shell_command is "" then
	end if
	set default_command to shell_command
	if _range as text = "" then
		set text_content to text of front document
		set results to executeCommand(shell_command, text_content)
		set text of front document to results
		return ""
		set text_content to _range as text
		set results to executeCommand(shell_command, text_content)
		return results
	end if
end RunFromBBEdit

on executeCommand(shell_command, text_content)
	set AppleScript's text item delimiters to {ASCII character 13}
	set results_text to text items of (do shell script "echo " & quoted form of text_content & " | " & shell_command)
	set AppleScript's text item delimiters to {ASCII character 10}
	set return_text to text items of results_text as text
	set AppleScript's text item delimiters to {""}
	return return_text
end executeCommand
Collin Donnell @collin