Textmate command line launcher for zsh

Fletch on 2009-03-20T15:13:46

Because I really miss being able to gnuclient +23 foo (for which there at least is mate --line 23 foo) or vim +/pat bar (which mate can't do) I whipped this up. Maybe someone will find it useful.

##
## ma -- textmate launcher that works like 'vi +line file' or 'vi +/re file'
##
ma () {
  emulate -L zsh
  setopt extended_glob

  local line="" column="" url="txmt://open?url=" term=""
  local usage="usage: ma [+line[:col]] file"

  if (( # == 0 )) ; then
    print "$usage"
    return 1
  fi

  if [[ "$1" = (#b)+([0-9]##)(:([0-9]##)#)# ]] ; then
    shift ## eat $1
    line="$match[1]"
    [[ -n "$match[3]" ]] && column="$match[3]"
  elif [[ "$1" = (#b)+/(*) ]] ; then
    shift
    local term="$match[1]"
  fi

  if [[ -z "$1" ]] ; then
    print "$usage"
    return 1
  fi

  file="$1" ; shift
  [[ "$file" != /* ]] && file="${PWD}/$file"

  if [[ -n "$term" ]] ; then
    local -a maybe_line
    maybe_line=( "${(s,:,)$(perl -lne 'BEGIN{$p=shift;$p=qr/($p)/}if( /$p/ ){$c=$-[1]+1;print "$.:$c";exit 0}END{exit 1;}' -- "$term" "$file")}" )
    if [[ -z "$maybe_line" ]] ; then
      print "No match for '$term' found in '$file'"
      return 1
    else
      line="$maybe_line[1]"
      column="$maybe_line[2]"
    fi
  fi

  url="${url}file:///$file"

  [[ -n "$line" ]] && url="${url}&line=$line"
  [[ -n "$column" ]] && url="${url}&column=$column"

  open "$url"
}

ma "$@"