github.com/ladydascalie/elvish@v0.0.0-20170703214355-2964dd3ece7f/edit/hooks.go (about)

     1  package edit
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/elves/elvish/eval"
     8  )
     9  
    10  // The $le:{before,after}-readline lists that contain hooks. We might have more
    11  // hooks in future.
    12  
    13  var _ = registerVariable("before-readline", makeListVariable)
    14  
    15  func (ed *Editor) beforeReadLine() eval.List {
    16  	return ed.variables["before-readline"].Get().(eval.List)
    17  }
    18  
    19  var _ = registerVariable("after-readline", makeListVariable)
    20  
    21  func (ed *Editor) afterReadLine() eval.List {
    22  	return ed.variables["after-readline"].Get().(eval.List)
    23  }
    24  
    25  func makeListVariable() eval.Variable {
    26  	return eval.NewPtrVariableWithValidator(eval.NewList(), eval.ShouldBeList)
    27  }
    28  
    29  func callHooks(ev *eval.Evaler, li eval.List, args ...eval.Value) {
    30  	if li.Len() == 0 {
    31  		return
    32  	}
    33  
    34  	opfunc := func(ec *eval.EvalCtx) {
    35  		li.Iterate(func(v eval.Value) bool {
    36  			fn, ok := v.(eval.CallableValue)
    37  			if !ok {
    38  				fmt.Fprintf(os.Stderr, "not a function: %s\n", v.Repr(eval.NoPretty))
    39  				return true
    40  			}
    41  			err := ec.PCall(fn, args, eval.NoOpts)
    42  			if err != nil {
    43  				// TODO Print stack trace.
    44  				fmt.Fprintf(os.Stderr, "function error: %s\n", err.Error())
    45  			}
    46  			return true
    47  		})
    48  	}
    49  	ev.Eval(eval.Op{opfunc, -1, -1}, "[hooks]", "no source")
    50  }