]> git.lizzy.rs Git - micro.git/commitdiff
Add textfilter command
authorZachary Yedidia <zyedidia@gmail.com>
Thu, 19 Dec 2019 15:22:31 +0000 (10:22 -0500)
committerZachary Yedidia <zyedidia@gmail.com>
Wed, 25 Dec 2019 22:05:11 +0000 (17:05 -0500)
internal/action/command.go

index 37ff0788925b086e5ace5ce211f3038208ecf8e0..385fe6b03bed2ff94f9baf0430c40499cb674784 100644 (file)
@@ -5,6 +5,7 @@ import (
        "errors"
        "fmt"
        "os"
+       "os/exec"
        "path/filepath"
        "regexp"
        "strconv"
@@ -64,6 +65,7 @@ func InitCommands() {
                "memusage":   Command{(*BufPane).MemUsageCmd, nil},
                "retab":      Command{(*BufPane).RetabCmd, nil},
                "raw":        Command{(*BufPane).RawCmd, nil},
+               "textfilter": Command{(*BufPane).TextFilterCmd, nil},
        }
 }
 
@@ -240,6 +242,33 @@ func (h *BufPane) RawCmd(args []string) {
        Tabs.SetActive(len(Tabs.List) - 1)
 }
 
+// TextFilterCmd filters the selection through the command.
+// Selection goes to the command input.
+// On successfull run command output replaces the current selection.
+func (h *BufPane) TextFilterCmd(args []string) {
+       if len(args) == 0 {
+               InfoBar.Error("usage: textfilter arguments")
+               return
+       }
+       sel := h.Cursor.GetSelection()
+       if len(sel) == 0 {
+               h.Cursor.SelectWord()
+               sel = h.Cursor.GetSelection()
+       }
+       var bout, berr bytes.Buffer
+       cmd := exec.Command(args[0], args[1:]...)
+       cmd.Stdin = strings.NewReader(string(sel))
+       cmd.Stderr = &berr
+       cmd.Stdout = &bout
+       err := cmd.Run()
+       if err != nil {
+               InfoBar.Error(err.Error() + " " + berr.String())
+               return
+       }
+       h.Cursor.DeleteSelection()
+       h.Buf.Insert(h.Cursor.Loc, bout.String())
+}
+
 // TabSwitchCmd switches to a given tab either by name or by number
 func (h *BufPane) TabSwitchCmd(args []string) {
        if len(args) > 0 {