# history - provide a little control over the last word of the last 
#           commands.   !$ matches the last word in the last line typed
#           insert it as many times as desired.
# version 1.0
#           Now you can use !0 !1 !2  etc.. as well as !$  The numbers are 
#           restricted to the range 0 thru 9.  
#           Also !* expands to the whole line..
# version 2.0
#           by Ian Frechette and Matthew Green
# version 2.1
#           Fixed !* to not include the first word, and added !!

@ hs.on = 1
@ hs.lline - []
bind ^K meta3
#bind meta3-h parse @ hs.on = 1 - hs.on
bind meta3-h parse @ hs.on = 1 - hs.on;if (hs.on) { ^set -status_user1 } { ^set status_user1  - no history }

set input_protection off
on ^input * if (hs.on) { sendline $hs.eval($*) } { sendline $* }

alias allbutfirst @ function_return = [$1-]

alias hs.eval
{
	@hs.line = [$*]
	@hs.mark = index(! $hs.line)
	@ hs.nline = []
	if (@hs.line)
	{
		while (hs.mark > -1)
		{
			@hs.nline = hs.nline ## left($hs.mark $hs.line)
			@hs.num = mid(${hs.mark+1} 1 $hs.line)
			if (index(0123456789*!$$ $hs.num) > -1)
			{
				if (hs.num == [$$])
				{
					@hs.word = word(${#hs.lline-1} $hs.lline)
				}
				{
				if (hs.num == [!])
				{
					@hs.word = hs.lline
				}
				{
				if (hs.num == [*])
				{
					@hs.word = allbutfirst($hs.lline)
				}
				{
				 	@hs.word = word($hs.num $hs.lline)
				} } }
				@hs.nline = hs.nline ## hs.word
				@hs.line = mid(${hs.mark + 2} 999 $hs.line)
			}
			{
				@hs.nline = hs.nline ## [!]
				@hs.line = mid(${hs.mark + 1} 999 $hs.line)
			}
			@hs.mark = index(! $hs.line)
		}
		@ hs.nline = hs.nline ## hs.line
		@ hs.lline = hs.nline
	}
	@ function_return = hs.nline
}

