From c61a6995a220b9b105ace10c134ccead7a080a19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mickae=CC=88l=20Menu?= Date: Tue, 19 Jan 2021 19:59:03 +0100 Subject: [PATCH] Proof of concept for filtering notes interactively with fzf --- core/note/filter.go | 70 +++++++++++++++++++++++++++++++++++++++++++++ core/note/list.go | 4 +-- 2 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 core/note/filter.go diff --git a/core/note/filter.go b/core/note/filter.go new file mode 100644 index 0000000..283a516 --- /dev/null +++ b/core/note/filter.go @@ -0,0 +1,70 @@ +package note + +import ( + "fmt" + "io" + "os" + "os/exec" + + "github.com/mickael-menu/zk/adapter/tty" + "github.com/mickael-menu/zk/core/style" + "github.com/mickael-menu/zk/util/strings" +) + +func WithMatchFilter(callback func(func(Match) error)) ([]string, error) { + styler := tty.NewStyler() + + return withFilter(func(w io.Writer) { + callback(func(m Match) error { + fmt.Fprintf(w, "%v\x01 %v %v\n", + m.Path, + styler.MustStyle(m.Title, style.Rule("yellow")), + styler.MustStyle(strings.JoinLines(m.Body), style.Rule("black")), + ) + return nil + }) + }) +} + +func withFilter(callback func(w io.Writer)) ([]string, error) { + zkBin, err := os.Executable() + if err != nil { + return []string{}, err + } + + cmd := exec.Command( + "fzf", + "--delimiter", "\x01", + "--tiebreak", "begin", + "--ansi", + "--exact", + "--height", "100%", + // FIXME: Use it to create a new note? Like notational velocity + // "--print-query", + // Make sure the path and titles are always visible + "--no-hscroll", + "--tabstop", "4", + // Don't highlight search terms + "--color", "hl:-1,hl+:-1", + // "--preview", `bat -p --theme Nord --color always {1}`, + "--preview", zkBin+" list -f {{raw-content}} {1}", + "--preview-window", "noborder:wrap", + ) + cmd.Stderr = os.Stderr + + w, err := cmd.StdinPipe() + if err != nil { + return []string{}, err + } + go func() { + callback(w) + w.Close() + }() + + output, err := cmd.Output() + if err != nil { + return []string{}, err + } + + return strings.SplitLines(string(output)), nil +} diff --git a/core/note/list.go b/core/note/list.go index 5e4c923..53ff6b2 100644 --- a/core/note/list.go +++ b/core/note/list.go @@ -130,8 +130,8 @@ type matchRenderContext struct { Title string Lead string Body string - RawContent string - WordCount int + RawContent string `handlebars:"raw-content"` + WordCount int `handlebars:"word-count"` Snippet string Created time.Time Modified time.Time