My intention is that this plugin can be run when a single selection is made in the document, and after having been run, all lines containing that selection will no longer be in the document. This plugin has a dependency on the grep command being available. The plugin, based on "external command" (found on this forum), should be passing the entire document through "grep -v <selection>" to perform the filter.
My current attempt looks like:
- Code: Select all
import sublime
import sublime_plugin
import subprocess
# view.run_command('selection_filter')
class SelectionFilterCommand(sublime_plugin.TextCommand):
def run(self, edit):
regions = self.view.sel()
if len(regions) == 1 and not regions[0].empty():
self.runFilter(edit, regions[0])
def runFilter(self, edit, textToFilter):
command = "grep -v " + textToFilter
document = sublime.Region(0, self.view.size())
p = subprocess.Popen(command, shell=True, bufsize=-1,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output, error = p.communicate(self.view.substr(document).encode('utf-8'))
if error:
sublime.error_message(error.decode('utf-8'))
else:
self.view.replace(edit, document, output.decode('utf-8'))
Problem #1: when I try to run this with a single word selected, I receive the following error:
Traceback (most recent call last):
File ".\sublime_plugin.py", line 282, in run_
File ".\selection_filter.py", line 10, in run
self.runFilter(edit, regions[0])
File ".\selection_filter.py", line 14, in runFilter
command = "grep -v " + textToFilter
TypeError: cannot concatenate 'str' and 'Region' objects
I've no idea how to address this.
Problem #2: Currently I'm not doing any sanity checking on the selection other than making sure there's only one, and it's not empty. Once problem#1 is solved, this will be an issue since the selection could be, for example, "word1 word2" which would create an external command of "grep -v word1 word2" and this would fail, looking for file `word2` to grep in, probably destroying the current edit buffer. How to I make sure my selection (regions[0]) does not contain any space, newline, or other special characters (such as an ampersand or semi-colon)?
Thanks much...
mah
