Sunday, July 8, 2012

Shell script - Capture snippets from vi or Vim

Here is a utility that may be useful to people who use vi or Vim.
Perl Squirrel has a common tendency of collecting useful code samples and this tool enables that without too much time or effort.  The general idea is this... While editing code, highlight the code sample worth keeping and file it in a text file without leaving the vi or Vim environment. 

Here are the requirements for this utility:
  • You use 'vi' or 'Vim'
  • Create a subdirectory called "notes" under your home directory
  • Place the "" utility in your personal 'bin' directory or somewhere in your PATH

Here is the code: (See Instructions in the code comments)
#!/bin/bash #Script: #Purpose: Grab certain lines of text from the file # you are editing/viewing in vi/vim, # and append this snippet to a notes file. # #How to use in vi/vim session: # Position cursor on 1st line to save, press the letters # ma # Position cursor on last line to save, press the letters # mb # Capture the snippet to the default ~/notes/snippet.txt file # :'a,'b w ! # Or, Capture the snippet to a specified file ~/notes/favorite.txt # :'a,'b w ! favorite ["Optional Short description"] # #This code assumes you will store the snippets in a "notes" #subdirectory under your home directory. #Place this code in your personal bin directory, or in your PATH. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SNIP=${1:-snippet} DESC="${2:-UNNAMED SNIPPET}" echo '#[SNIP]------------------------------------' >> ~/notes/${SNIP}.txt echo "#[SNIP] ${DESC} " >> ~/notes/${SNIP}.txt echo '#[SNIP]------------------------------------' >> ~/notes/${SNIP}.txt cat - >> ~/notes/${SNIP}.txt