# Description: adds configurable text hilighting

require >= 2.0

procs command_hilight

AddToPrefs beeponhilight bool 0
global prefs
set prefs(hilight) ""

proc command_hilight {window line} {
    global prefs
    set line [rele [split [string tolower $line]]]
    if {$line == ""} {
        Echo $window "\[ info \] Hilighting words: [string map {* ""} [join $prefs(hilight)]]" {info default}
        return
    }
    foreach word $line {
        if {[string match "-*" $word]} {
            set word [string range $word 1 end]
            set index [lsearch -exact $prefs(hilight) *$word*]
            if {$index == -1} {
                Echo $window "\[ info \] \"$word\" not in hilight list" {info default}
                return
            }
            set prefs(hilight) [lreplace $prefs(hilight) $index $index]
            Echo $window "\[ info \] \"$word\" removed from hilight list" {info default}
        } else {
            set index [lsearch -exact $prefs(hilight) *$word*]
            if {$index != -1} {
                Echo $window "\[ info \] \"$word\" already in hilight list" {info default}
                return
            }
            Echo $window "\[ info \] Now hilighting \"$word\"" {info default}
            lappend prefs(hilight) *$word*
        }
    }
}

proc hilight {win} {
    global prefs me info
    if {[$win tag nextrange me end-1l] != ""} {return}
    set line [$win get end-1l end]
    foreach x "*$me* $prefs(hilight)" {
        if [string match -nocase $x $line] {
            $win tag add hilight end-1l end
            Event hilight "x word line line info(channel,$win) channel"
            if $prefs(beeponhilight) {bell}
            break
        }
    }
}

proc unload { } {
    global on info
    RemoveFromPrefs beeponhilight
    unbind Text <<echo>> "[namespace current]::hilight %W"
    catch {unset on(hilight)}
    set index [lsearch $info(on) {hilight 0}]
    set info(on) [lreplace $info(on) $index $index]
}

proc help {window line} {
    switch -exact -- $line {
        default {
            Echo $window {[ help ] Variables added by this script: BEEPONHILIGHT} {help default}
            Echo $window {[ help ] Sets whether to ring the bell when a line is hilighted} {help default}
            Echo $window {[ help ] Commands added by this script: /hilight} {help default}
            Echo $window {[ help ] Usage: /hilight [[-]<word>] [[-]<word>...]} {help default}
            Echo $window {[ help ] Displays, adds, or removes words that will be hilighted} {help default}
            Echo $window {[ help ] Events added by this script: hilight. Variables: $word $line $channel} {help default}
        }
    }
}

global info
lappend info(on) {hilight 0}
bind Text <<echo>> "[namespace current]::hilight %W"
