Python – Create your own Snippet Manager.

How NOT to type the same text over, and over, and over....
Febuary 09, 2019

Do you know someone who enters the same text over and over again? Maybe a medical tech who types the same medication name 50 times a day? Or someone who enters the same shipping address 30 times a week? A legal assistant who works long into the night typing the same verbiage in contract after contract? Or maybe it's YOU who finds yourself entering the same code over and over again?


What if you could have a small window on your desktop with a list of the things that you enter repetitively? You could just click on the item to copy it to the clipboard. Then right click on your document, and the click 'Past'.

You could trade a few dozen keystrokes for just 3 mouse clicks!! No having to check for misspellings, or missed typed words. Fast, Simple, and Easy.

Will, such a thing is called a Snippet Manager. And this blog posts explains how to make a very simple one using python.

The word 'Snippet' has a number of different meanings depending on the context in which it is used. But in this case we are using the word to mean a small re-usable bit of computer code or a string of re-usable text. A Snippet Manager is a program that allows the user to select from a pre-saved list of snippets, so the text does not need to be re-typed over and over again.

Many text/code editors have Snippet Managers built in. Usually with a very nice interface that allows the user to easily add their snippets to a save file.

Unfortunately, Idle (the code editor that comes pre-packaged with python) does not have one. But you can use the snippet.py script (bellow) to create your own.


How to uses snippet.py:

The python script (snippet.py) shown below, is a VERY simple example of a Snippet Manager. Please feel free to use it as a starting point to make your own.

To use it, run the script, and then move the window someplace out of the way on the right side of your screen. Click on an item you want from the list, this will copy the text to the clipboard. Then right-click on you document, website forum, email or whatever you want to past the text. The right-click should bring up a menu. And then just click 'Past'.

To add or change items on the list, edit the script following the examples I already have. And as always, be sure to also make a backup of your files.

I acknowledge that hard-coding your snippets into a script like this is a somewhat less elegant solution than using an 'add snippet interface'. But this is very simple, easy to learn and uses, and will work with anything that can accept text from the clipboard. And best of all, it's FREE.

A case study; using a Snippet Manager to save valuable time.

Let us say that Alice (imaginary person) is the owner/manager of Alice's Flower Shop. Alice ships flower arrangements to her customers. She also orders supplies from several vendors and hobby shops. So Alice spends a few minutes every day carefully entering shipping address on her laptop, and carefully checking to be sure that she entered them correctly. Alice is spending an average of 12 minutes every day (Monday through Friday) doing this task. Most of the address that she enters are the same two dozen or so, over and over.

When asked about this, she says that's it no big deal; just part of doing business.

So, if she is averaging 12 minutes a day on this task, and she works 5 days a week, then she is spending 1 hour (on average) every week doing this task.

Now, if she works 50 weeks a year, that means that she is spending 50 hours, or a little over 6 work days a year (assuming an 8 hour work day) doing this task. That's more time than she took off for vacation last year. That is valuable time taken away from creating her product, and growing her business.

Now, she is thinking that maybe this really is a big deal.

So, if Alice adds her reoccurring shipping address to a Snippet Manager, and gets in the habit of using it, she can significantly reduce the time she spends daily entering and checking these strings. The Snippet Manager removes any possibility of mis-typing these string of text.

If Alice can reduce the time spent on this task to an average of 30 second a day, that works out to be about 2 work hours a year, as opposed to 6 work days.

Entering shipping address is just one of Alice's many daily and weekly computer tasks. How many others can she simplify using a simple Snippet Manager. How much production time can she save.

This is of course just an imaginary case study. But I hope it illustrates how something as simple as this little home-brewed Snippet Manager can be used as a very valuable, time saving, production tool.


try:
    from Tkinter import *
except ImportError:
    from tkinter import *
import datetime
import uuid

"""
snippets.py

Written by Joe Roten, 2019-02-04

This code is intended to be a 'starting point'
for people to create their own simple
Snippet Manager.

Clicking on an item in the listbox will
copy text to the clipboard.

"""

snippets = {}


# See the 'if' statments in SubClick() to see how these codes work.
# Please feel free to add your own codes.

snippets['* Todays Date (YYYY-MM-DD)'] = "*Code101"
snippets['* Todays Date (Full)'] = "*Code102"
snippets['* A unique UUID4 code'] = "*Code103"

# A few examples of short shippets.

snippets['Hydrocodone-Acetaminophen 30mg'] = 'Hydrocodone-Acetaminophen 30mg'
snippets['Dr. James K. Hollman'] = 'Dr. James K. Hollman'
snippets['Bariatric surgery'] = 'Bariatric surgery'
snippets['National Zoological Society'] = 'National Zoological Society'
snippets['www.python.org'] = 'www.python.org'

# Here are a few examples of a block of text.

snippets['+ My Shipping Address'] = """
Learn2Program.net
PO Box 82337
Kenmore, WA 98028-2337
"""

snippets['+Py: Read file into a list.'] = """
# Read a file into a list.
with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()
"""

snippets['+Py: For Loop Example.'] = """
# For Loop Example.
for x in range(0, 3):
    print "We're on time %d" % (x)
"""

# Here is an example of a paragraph of text.
# This could be standard text used in legal papers,
#   or copyright verbage, or instructions on taking medication,
#   etc.

snippets['+ Tarzan, Paragraph One'] = """
I had this story from one who had no business to tell it to me, or to any other. I may credit the seductive influence of an old vintage upon the narrator for the beginning of it, and my own skeptical incredulity during the days that followed for the balance of the strange tale.
"""





def SubClick(event):
    """This function runs when an item on the list is selected."""
    try:
      index = listbox.curselection()[0]
      seltext = listbox.get(index)
      result = snippets.get(seltext, "Unknown Value")
      # Todays Date (YYYY-MM-DD)
      if result == "*Code101":
          result = datetime.datetime.now().date()
      # Todays Date (Full)          
      if result == "*Code102":
          result = datetime.datetime.now().strftime("%A, %B %d, %Y")
      # A unique UUID4 code          
      if result == "*Code103":
          result = str(uuid.uuid4())
      # Copy the result to the clipboard.
      master.clipboard_clear()
      master.clipboard_append(result)
      master.update()      
    except:
      pass  



if __name__ == '__main__':

  master = Tk()
  master.geometry("250x200")
  master.title("snippets.py")

  # Create the listbox.
  frame = Frame(master)
  scrollbar = Scrollbar(frame, orient=VERTICAL)
  listbox = Listbox(frame, yscrollcommand=scrollbar.set)
  scrollbar.config(command=listbox.yview)
  scrollbar.pack(side=RIGHT, fill=Y)
  listbox.pack(side=LEFT, fill=BOTH, expand=1)
  frame.pack(fill=X)
  listbox.bind("", SubClick)
  listbox.bind("<>", SubClick)

  # Add the text to the bottom of the window.
  w = Label(master, text="Click on an item to copy\n it to the clipboard.")
  w.pack()

  # Populate the listbox with the list.
  keylist = list(snippets.keys())
  keylist.sort()
  for key in keylist:
    listbox.insert(END, key)

  # tkinter mainloop
  mainloop()


Last updated: 2019-02-09

Written by Joe Roten

Computer tech, Graphic Artist, Photographer, Writer, Educator, Programmer, Jack of many trades, Social gadfly, and Scholar without portfolio. http://www.gsw7.net/joe/

Written by Joe Roten

http://www.gsw7.net/joe/

As always

The information on my website is FREE.
But donations to help pay for Coffee and Beer are always welcomed.
Thanks.