Welcome

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

Changing the Finder "Open With" contextual menu from the command line

The command line tool duti (http://duti.sourceforge.net) can be used to change default file-application launching associations as shown by the Finder "Open With" contextual menu. Changing the Finder "Open With" contextual menu means changing the default way we "open" documents on the command line as well.

The "lsregister" command can be used to dump or rebuild the Launch Services database.

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
export IFS=$' \t\n'


# download & install duti, MacVim and TextMate

# duti - set default UTI handlers
# cf. http://duti.sourceforge.net/documentation.php and
# http://developer.apple.com/macosx/uniformtypeidentifiers.html

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/duti/duti-1.3.0.pkg.tar.gz
tar -xzf duti-1.3.0.pkg.tar.gz
open -a Installer duti-1.3.0.pkg
stat -x /usr/local/bin/duti
duti -h
man duti


# MacVim, http://code.google.com/p/macvim/

cd ~/Desktop
curl -L -O http://macvim.googlecode.com/files/MacVim-7_2-stable-1_2.tbz
tar -xjf MacVim-7_2-stable-1_2.tbz
#open MacVim-7_2-stable-1_2.tbz    # uses BOMArchiveHelper (10.4) or Archive Utility (10.5) respectively
mv -i MacVim-7_2-stable-1_2 MacVim
mv -i ~/Desktop/MacVim /Applications


# TextMate, http://macromates.com

cd ~/Desktop
curl -L -O http://macromates.com/textmate/files/TextMate_1.5.7.dmg
hdiutil mount ~/Desktop/TextMate_1.5.7.dmg
cp -Ri '/Volumes/TextMate 1.5.7/TextMate.app' /Applications
hdiutil unmount '/Volumes/TextMate 1.5.7'
#/usr/bin/sudo /bin/ln -s /Applications/TextMate.app/Contents/Resources/mate /usr/local/bin/mate


# get the path to the "lsregister" command
locate lsregister | head -n 1
find /System/Library/Frameworks -type f -name lsregister -ls
find /System/Library/Frameworks/CoreServices.framework -type f -name lsregister -ls

alias lsregister="/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"

#/usr/bin/sudo /bin/ln -s `locate lsregister | head -n 1` /bin/lsregister   # alternative

# rebuild Launch Services database
#alias rlsdb='lsregister -kill -r -f -all system,local,user'    # Mac OS X 10.5; cf. http://9stmaryrd.com/2008/05/16/158
alias rlsdb='lsregister -kill -r -f -domain local -domain system -domain user'

rlsdb

lsregister -h

lsregister -dump | grep -i duti
lsregister -dump | grep -i MacVim
lsregister -dump | grep -i TextMate
lsregister -dump | grep -i TextEdit
lsregister -dump | grep -i Safari
lsregister -dump | grep -i helpviewer


lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*)$/  \1/p' | sort | uniq | nl
lsregister -dump | grep '[[:space:]]uti:' | awk '{ print $2 }' | sort | uniq | nl
lsregister -dump | sed -E -n -e 's/^.*identifier:[[:space:]]+([^[:space:]].*)$/  \1/p' | sort | uniq | nl
lsregister -dump | sed -E -n -e 's/^.*path:[[:space:]]+([^[:space:]].*\.app)$/  \1/p' | sort | uniq | nl


lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*)$/  \1/p' | nl | egrep -i 'duti|MacVim|TextMate|TextEdit|Safari|helpviewer'
lsregister -dump | sed -E -n -e 's/^.*identifier:[[:space:]]+([^[:space:]].*)$/  \1/p' | nl | egrep -i 'duti|MacVim|TextMate|TextEdit|Safari|helpviewer'
lsregister -dump | sed -E -n -e 's/^.*path:[[:space:]]+([^[:space:]].*\.app)$/  \1/p' | nl | egrep -i 'duti|MacVim|TextMate|TextEdit|Safari|helpviewer'


lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(public\..*)$/  \1/p' | sort | uniq | nl
lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*text.*)$/  \1/p' | sort | uniq | nl


alias utis="lsregister -dump | grep '[[:space:]]uti:' | awk '{ print \$2 }' | sort | uniq"
alias utis="lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*)$/\1/p' | sort | uniq"
utis

utis | grep -i 'public\.' | nl

defaults read com.apple.LaunchServices


# move & copy the same file
unset -f mc
function mc() {
   if [[ $# -gt 1 ]] || [[ ! -e "$@" ]]; then return 1; fi
   tmpfile="${@}.tmp-${RANDOM}"
   printf "%s\n" "$tmpfile"
   /bin/mv "$@" "${tmpfile}"
   /bin/sleep 0.2
   /bin/cp -p "${tmpfile}" "$@"
   /bin/rm "${tmpfile}"
   return 0
}


unset -f mc
function mc() {
   if [[ $# -gt 1 ]] || [[ ! -e "$@" ]]; then return 1; fi
   tmpfile="/tmp/tmpfile.tmp-${RANDOM}"
   printf "%s\n" "$tmpfile"
   /bin/mv "$@" "${tmpfile}"
   /bin/sleep 0.2
   /bin/cp -Rp "${tmpfile}" "$@"
   /bin/rm -Rf "${tmpfile}"
   return 0
}



echo hello world > ~/Desktop/test.txt
echo hello world > ~/Desktop/test.html


# switch between Safari & Help Viewer as the default launching app for html files
open ~/Desktop/test.html


# cf. http://duti.sourceforge.net/documentation.php

printf "%s\n" 'com.apple.helpviewer   public.html   all' | duti     
mc ~/Desktop/test.html
open ~/Desktop/test.html

printf "%s\n" 'com.apple.Safari   public.html   all' | duti
mc ~/Desktop/test.html
open ~/Desktop/test.html

rlsdb


# switch between TextEdit, MacVim & TextMate as the default launching app for plain text files

open ~/Desktop/test.txt

printf "%s\n" 'com.macromates.textmate   public.plain-text   all' | duti
open ~/Desktop/test.txt
mc ~/Desktop/test.txt

printf "%s\n" 'org.vim.MacVim   public.plain-text   all' | duti
open ~/Desktop/test.txt    # type: ":q" or ":x" to quit test.txt
mc ~/Desktop/test.txt

printf "%s\n" 'com.apple.TextEdit   public.plain-text   all' | duti
open ~/Desktop/test.txt
mc ~/Desktop/test.txt



# cf. http://duti.sourceforge.net/documentation.php

/bin/cat > ~/Desktop/test.duti <<-'EOF'
com.apple.helpviewer   public.html   all
com.macromates.textmate   public.plain-text   all
EOF

# remove white space at line beginning
ed -s ~/Desktop/test.duti <<< $',s/^[[:space:]]*//\nw'

open -e ~/Desktop/test.duti

duti -v ~/Desktop/test.duti

mc ~/Desktop/test.html
open ~/Desktop/test.html

mc ~/Desktop/test.txt
open ~/Desktop/test.txt


#--------------------------------------------------


# GUI alternative to switch the default launching app for a single file
[right-click on a file] + [alt]  ->  "Always Open With"

# GUI alternative to change the default launching app for all files of the same kind
[right-click on a file] -> "Get Info" -> "Open with:" -> [select an app] -> "Change All ..."

Using Juice with Mozilla Ubiquity

Thanks to Wenmao Zhang, Juice now works with Mozilla Ubiquity:

1. Install both Juice (http://juiceapp.com) and Ubiquity
2. Press control+space (or whichever keyboard shortcut used for Ubiquity) to open the Ubiquity window
3. Input "command-editor" in the window, select "command-editor" and press enter
4. In the command editor view, copy and paste the code listed below (click somewhere outside the text input area to save)
5. Reopen the Ubiquity window and input "juice <your keywords>" (for example: juice Julia Roberts) and hit enter.
7. Enjoy!

CmdUtils.CreateCommand({
  name: "juice",
  icon: "chrome://juice/skin/images/titlebar/logo16x16.png",
  takes: {"keywords": noun_arb_text},
  description: "Just Juice it!",
  execute: function(a) {
    var overlay = window.parent.juiceapp_linkoolDragAndDrop._overlay;
    var dnd = window.parent.juiceapp_linkoolDragAndDrop;
    var monitor = window.parent.juiceapp_SearchEngineMonitor;
    overlay.alertUserWhenAction(overlay.ACTION_DDKEYWORD);
    dnd.invokeLinkoolWindow(a.text,"searchDropKey",1,"",1,false, true);
    monitor.resetCurrentStatusInfo();
  },
  preview: function(previewBlock, directObj) {
    var statusText = directObj.text;
    var previewTemplate = "Juice Me: <b>${status}</b>";
    var truncateTemplate = "";
    var previewData = {
      status: statusText
    };

    var previewHTML = CmdUtils.renderTemplate(previewTemplate, previewData);
    previewBlock.innerHTML = previewHTML;
  }
});

Convert an object to an associative array

// Converts a php object to an associative array

function object_to_array($data) 
{
  if(is_array($data) || is_object($data))
  {
    $result = array(); 
    foreach($data as $key => $value)
    { 
      $result[$key] = object_to_array($value); 
    }
    return $result;
  }
  return $data;
}

// insert code here..

Get Arguments Passed To A Function

Javascript function can accept arguments which are not specified in the parameter list

function someFunc()
{
var firstArg = someFunc.arguments[0];
var secondArg = someFunc.arguments[1];
....
}

Select a random record from a MySQL database

// description of your code here
I needed to select 5 random records from a MySQL database and found this little squib of code from http://peterfreitag.com/item/466.cfm

SELECT column FROM table ORDER BY RAND() LIMIT 5

kv - launch Keyboard Viewer

locate -i *keyboardviewerserver

alias kv='/usr/bin/open /System/Library/Components/KeyboardViewer.component/Contents/SharedSupport/KeyboardViewerServer.app'

kv


# cf. Accented letters and other symbols on the Mac,
# http://mac4translators.blogspot.com/2008/08/accented-letters-and-other-symbols-on.html

[cmd]     #  hold the command key
[alt]
[alt][shift]

Excerpt from article

// Useful form if you want to know how to pull an excerpt of an article onto an existing article/webpage

<h1><txp:title /></h1>
<txp:excerpt />
				
<p class="moreinfo"><txp:permlink>##more_info##</txp:permlink></p>

sitemap

// Sitemap Form that will show the Section title and the list of articles for that section.

<txp:if_article_section name="sitemap">

<txp:else />
<txp:if_different>


   </ul><h2><txp:section title="1" /></h2><ul>

</txp:if_different>

   <li><txp:permlink><txp:title /></txp:permlink></li> 

</txp:if_article_section>


// Sitemap Page template looks like this;

     <div id="content">
<h1>Sitemap</h1>
<ul style="display:none;"><txp:article_custom limit="99999" form="sitemap" sort="section asc,Posted asc" /></ul>	

    </div><!-- content -->	

pcregrep - UTF-8 aware grep replacement

# we first have to download, compile & install the PCRE library, cf. http://www.pcre.org/pcre.txt
# requirement: Xcode, http://developer.apple.com/tools/xcode/index.html

cd ~/Desktop
/usr/bin/curl -L -O http://downloads.sourceforge.net/pcre/pcre-7.7.tar.gz
/usr/bin/tar -xzf pcre-7.7.tar.gz
cd pcre-7.7
./configure --help
./configure --prefix=/usr/local --enable-utf8 --enable-unicode-properties
# for Intel Macs, see http://hivelogic.com/articles/2005/12/ruby_rails_lighttpd_mysql_tiger
#./configure --prefix=/usr/local --enable-utf8 --enable-unicode-properties CFLAGS=-O1
/usr/bin/make
/usr/bin/sudo /usr/bin/make install 


ls -l /usr/local/bin/pcregrep
stat -x /usr/local/bin/pcregrep

pcregrep --version
pcregrep --help
pcregrep --help | pcregrep -i 'utf-?8'
pcregrep --help | pcregrep -i multiline

man pcregrep
man pcrepattern
man pcretest
man perlretut

man pcregrep | less -p utf-8
man pcregrep | less -p multiline
man perlretut | less -p 'single line and multi'

open /usr/local/share/doc/pcre/html/pcregrep.html


# check if character set encoding of Terminal.app is set to UTF-8
if [[ "$(/usr/bin/defaults read com.apple.Terminal StringEncoding)" != "4" ]]; then 
   echo 'Terminal.app does not use UTF-8 character set encoding!'
   exit 1
fi


utf8str=$'caf\303\251'

printf $utf8str | /usr/bin/egrep -o '.'
printf $utf8str | /usr/local/bin/pcregrep -o '.'
printf $utf8str | /usr/local/bin/pcregrep -ou '.'     # UTF-8 aware

printf $utf8str | /usr/bin/egrep -o '.' | wc -l
printf $utf8str | /usr/local/bin/pcregrep -o '.' | wc -l
printf $utf8str | /usr/local/bin/pcregrep -ou '.' | wc -l     # UTF-8 aware

Tapping the Bash command line history

export PATH=/usr/bin:/bin:/usr/sbin:/sbin
export IFS=$' \t\n'


help fc
help history
help bind
help set
help shopt
open /usr/share/doc/bash/builtins.pdf


cp -ip ~/.bashrc ~/.bashrc.orig
cp -ip ~/.inputrc ~/.inputrc.orig
cp -ip ~/.bash_history ~/.bash_history.bak

cp -ip ~/.bashrc{,.orig}  # shortcut version
cp -ip ~/.inputrc{,.orig}
cp -ip ~/.bash_history{,.bak}


history
history | head -n 3
history | tail -n 1
history | egrep 5
history | egrep '^[[:space:]]*5'
history | egrep -m 1 '^[[:space:]]*5'
history | egrep '^[[:space:]]*5[[:space:]]+'

fc
fc -e nano
fc -l | nl
fc -ln | sed 's/^[[:space:]]*//'
fc -l 0
fc -l 1 -1
#exec /bin/bash     # ... in case of "fc: history specification out of range"
#source ~/.bash_login
fc -l -1
fc -l -5
fc -l 5 "cd "
fc -l -r 5 "cd "
fc -l -5 | grep cd | awk '{print $1}'
fc -s cd     # execute last cd command
fc -e vim 3
fc -e nano "cd "


set +o history   # disable adding commands to history list
set -o history   # enable adding commands to history list


/bin/cat >> ~/.bashrc <<-'EOF'

bind Space:magic-space     # enable option to expand & edit a command before running it by entering a [space]
#shopt -s histverify     # expand & edit a command before running it by entering [return]
shopt -s cmdhist
shopt -s histappend

# suppress history recording for the specified commands including commands beginning with a space
export HISTIGNORE="&:[ \t]*:ls:[bf]g:history*:clear:exit"

#export HISTCONTROL=ignorespace
#export HISTCONTROL=ignoredups
#export HISTCONTROL=ignoreboth

#PROMPT_COMMAND="history -a; ${PROMPT_COMMAND}"

EOF

source ~/.bashrc


/bin/cat >> ~/.inputrc <<-'EOF'

"\033[3~": delete-char             # get a proper forward delete key in Terminal.app
"\e[A": history-search-backward    # search command history backward with up arrow key
"\e[B": history-search-forward     # search command history forward with down arrow key

set show-all-if-ambiguous on        # enable tab completion with a single tab
set mark-symlinked-directories on
set completion-ignore-case on
#set visible-stats on
#set bell-style visible

#$if Bash   # same effect as "bind Space:magic-space" in ~/.bashrc
#  Space: magic-space
#$endif

EOF


exec /bin/bash    # reinitialize ~/.inputrc
source ~/.bash_login ~/.bashrc


help bind
bind -l | less
bind -P | less
bind -p | less    
bind -V | less
bind -v | less


# insert the last word of the previous command line
echo hello world1
echo hello world1 and world2
echo hello world1 and world2 and world3
echo hello
echo

[esc-.]     # press the esc-. key sequence repeatedly to iterate through the history list
[ctrl-u]    # clear the current command line
echo !$
printf "%s\n" $_


!1[space]            # expand the first command in the history list without executing
!12[space]           # expand command no. 12
sudo !![space]       # expand last command
!-4[space]           # expand the fourth last command
!cd[space]           # expand the last cd command
!?world?[space]      # expand the last command containing the specified word
!$[space]            # last word of the preceding command line
!:1[space]           # first argument of the preceding command
!-1:1[space]         # same
!-1:1-[space]        # all arguments of the previous command except the last on
!-1:1*[space]        # all arguments of the previous command
!-1:1-$[space]       # same
!-2:3[space]         # third argument from the command before the last one

abc def !#[space]     # double the entire command line typed so far

cd ~/Desktop
!cd:p
!cd[space]
[ctrl-u]
!?cd?:p                 # make the last cd command the last command in the history list and print it without executing
history | tail -n 1

cd[up_key]    
cp[up_key]              # hit the up & down arrow keys again and again to iterate through the commands
cp[down_key]           

[ctrl-r]cp              # press ctrl-r repeatedly to iterate through the previous commands
[esc] or [ctrl-j]       # quit searching with ctrl-r
[ctrl-k] + [ctrl-u]     # quit searching with ctrl-r and clear the command line
[ctrl-y]                # recalls the last string removed by ctrl-k or ctrl-u


# cf. http://nubyonrails.com/articles/2007/05/26/useful-shell-shortcuts
cp foo !#^.bak[space]            # !#^ refers to the first word after the command
cp -i foo !#^.bak[space]    
cp -p -i foo !#^.bak[space]    
cp !#$.bak[space] 
cp foo !#$.bak[space]            # !#$ refers to the preceding word
cp -i foo !#$.bak[space]    
echo abc def !#$.bak[space]
echo abc def !#$.bak ghi jkl !#$.foo mno[space]


# tab completion
#[tab]  # all available commands
#ds[tab]  # all available commands beginning with ds
#cd ~/Desktop
#cd ~/Des[tab]
#$[tab]  # all set system variables
#~[tab]  # users
#*[tab] 
#=[tab]
#/[tab]