/*
 * Name: Tab key Handlers
 * Originally by: Daemon
 * Rewritten for EPIC by: wc & archon
 * Modified for Drag0n by: CrackBaby
 * Purpose: To cache a list of users who recently messaged you. You can scroll
 * through the list by hitting the tab key.
 */

@ int.tlim = 5

/* prefix takes a list of words and returns the string (if any) that begins
 * all of them i.e. $prefix(blah123 blah456 blahlkwej blahfoo blahbar)
 * returns "blah"  - archon */

alias prefix {
/* find the longest word in the string */
  fe ($*) pp {
    @ lword = (strlen($pp) > strlen($lword)) ? pp : lword
  }
  @ wlen = strlen($lword)
  @ cont = 1
  @ nwords = numwords($*)
/* go through the longest word to find the first 
 * string that doesn't begin all the other strings */
  fec ($lword) pp {
    if (cont) {
      if (numwords($pattern($pfix$pp* $*)) == nwords) {
        @ pfix #= pp
      }{
        @ cont = []
      }
    }
  }
  @ function_return = pfix
  @ lword = wlen = cont = nwords = pfix = []
}

/* tabcomplete: when you hit tab, we look at your input line.  then we try
 * to complete your command based on what you're doing.
 */

/* I completely gutted this alias and rewrote it.  Now hitting tab with a
   blank input line cycles through msgs and hitting it any other time
   attempts to complete the word you're typing as a nick. - CB */

alias tabcomplete {
  /* Note that the wildcard mask "/msg % *" allows you to cycle your
     msg list or use the nick completer with /msg partial_nick. */
  if (!L || L =~ [/msg % *]) {
    getmsg 1
  } else {
    ^local fragment $rightw(1 $L)
    ^local before $beforew($fragment $L)
    type $^^{(before) ? [$before $getnick($fragment)] : getnick($fragment)}
  }
}

/* $getnick(<text fragment>)
   Given a fragment of a nickname on the current channel, return the
   full nick.  If multiple nicks match the fragment, return as many
   letters as the nicks have in common ($prefix()). -CB */

alias getnick {
  ^local completes
  fe ($chanusers()) nick {
    if (nick =~ [$0*]) {
      @ completes = [$nick $completes]
    }
  }
  @ function_return = prefix($completes)
}

alias addmsg {
  if (rmatch($0 $lst.tab)) {
    @ lst.tab = remw($0 $lst.tab)
    push lst.tab $0
  }{
    if (#lst.tab == int.tlim) {
      shift lst.tab
    }
    push lst.tab $0
  }
  @ tmp.tptr = #lst.tab - 1
  @ tmp.addn++
}

alias getmsg {
  if (!tmp.addn) {
    if ([$0]) {
      @ tmp.tptr = ((tmp.tptr - 1) < 0) ? #lst.tab - 1 : tmp.tptr - 1
    }{
      @ tmp.tptr = ((tmp.tptr + 1) >= #lst.tab) ? 0 : tmp.tptr + 1
    }
  }{
    @ tmp.addn = 0
  }
  type $(K)msg $^\^^word($tmp.tptr $lst.tab) 
}

alias getdes {
  if (!tmp.addn) {
    if ([$0]) {
      @ tmp.tptr = ((tmp.tptr - 1) < 0) ? #lst.tab - 1 : tmp.tptr - 1
    }{
      @ tmp.tptr = ((tmp.tptr + 1) >= #lst.tab) ? 0 : tmp.tptr + 1
    }
  }{
    @ tmp.addn = 0
  }
  type ${K}des $^\^^word($tmp.tptr $lst.tab) 
}
