I found this post when searching google to find out how to apply a unix command to a selection in sublime and it provided a great start for a solution. Here is a version of the original code that does the job. It’d be great if sublime could have a similar feature built in or this command bundled.
To use it, select some text and then from the console enter “view.run_command(‘external_filter’)”, sublime will prompt you for a command, enter a valid unix command and it will pipe your selection through the command and replace the text with it’s output.
import sublime
import sublime_plugin
import subprocess
# view.run_command('external_filter')
class ExternalFilterCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel('Command', '',
lambda command: self.runCommand(edit, command),
None, None)
def runCommand(self, edit, command):
regions = self.view.sel()
if len(regions) == 1 and regions[0].empty():
# No selection use the entire buffer
regions = [sublime.Region(0, self.view.size())]
for region in regions:
self.execCommand(edit, command, region)
def execCommand(self, edit, command, region):
p = subprocess.Popen(command, shell=True, bufsize=-1,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output, error = p.communicate(self.view.substr(region).encode('utf-8'))
if error:
sublime.error_message(error.decode('utf-8'))
else:
self.view.replace(edit, region, output.decode('utf-8'))