Using gedit to make a list of values into a set.

gedit is awesome;  the flexibility of the tool continues to impress me.  One problem I'm frequently faced with is a list of id values from some query, or utility, or e-mail message... and I want to do something with them.  So, for example I have:
but what I need is those id values as a sequence such as for use in an SQL IN expression or to assign to a Python set or list.  What I want is:
(10731,'10732', '10733', '10734', '10735', '10736', '10737',
'10738', '10739')
Reformatting a few numbers by hand isn't too hard - but what if I have a list of hundreds of id values? The answer, of course, is provided by gedit.  Under Tools -> Manage External Tools the user can build filters that can be applied to documents and have the results returned to gedit.  If I create a new external tool that accepts as input the "Current document" and as output has "Replace current document" then gedit will replace the contents of the current document with the results of the filter [pretty obvious;  and if it doesn't work I can always Ctrl-Z].  The body of the filter can be any script - a Python script is perfectly valid. Like this hack:
#!/usr/bin/env python
import sys

iteration = 0
line_length = 0
text = sys.stdin.readline()
while (text !=  ''):
  text = text.strip()
  if (len(text) > 0):
    if (iteration == 0):
      sys.stdout.write(', ') 
    if (line_length > 74):
      sys.stdout.write('\n ')
      line_length = 0
    if (len(text) > 0):
    line_length = line_length + len(text) + 4
    iteration = iteration + 1
  text = sys.stdin.readline()
The current document becomes the standard-input for the script and the standard-output of the script will replace the current document. The above hack reads in a list of lines and returns them as a set enumeration nicely wrapped to 80 characters per line. External tools are saved under names; for this one I saved it as "IN-Clause-Filter".
Now that I've setup the external tool every time I paste a list of id values into gedit I can simply select Tools -> External Tools -> IN-Clause-Filter and my list is instantly turned into a set enumeration.

No comments:

Post a Comment