]> git.lizzy.rs Git - micro.git/blobdiff - cmd/micro/terminal.go
Code optimisation (#1117)
[micro.git] / cmd / micro / terminal.go
index 06a24ce35850809cf743f87900e13bf60dd6b765..04ca1242576216dd5632bc8516542798f53720d4 100644 (file)
@@ -1,10 +1,12 @@
 package main
 
 import (
+       "bytes"
        "fmt"
        "os"
        "os/exec"
        "strconv"
+       "strings"
 
        "github.com/zyedidia/clipboard"
        "github.com/zyedidia/tcell"
@@ -27,6 +29,9 @@ type Terminal struct {
        status    int
        selection [2]Loc
        wait      bool
+       getOutput bool
+       output    *bytes.Buffer
+       callback  string
 }
 
 // HasSelection returns whether this terminal has a valid selection
@@ -56,18 +61,23 @@ func (t *Terminal) GetSelection(width int) string {
 }
 
 // Start begins a new command in this terminal with a given view
-func (t *Terminal) Start(execCmd []string, view *View) error {
+func (t *Terminal) Start(execCmd []string, view *View, getOutput bool) error {
        if len(execCmd) <= 0 {
                return nil
        }
 
        cmd := exec.Command(execCmd[0], execCmd[1:]...)
-       term, _, err := terminal.Start(&t.state, cmd)
+       t.output = nil
+       if getOutput {
+               t.output = bytes.NewBuffer([]byte{})
+       }
+       term, _, err := terminal.Start(&t.state, cmd, t.output)
        if err != nil {
                return err
        }
        t.term = term
        t.view = view
+       t.getOutput = getOutput
        t.vtOld = view.Type
        t.status = VTRunning
        t.title = execCmd[0] + ":" + strconv.Itoa(cmd.Process.Pid)
@@ -150,7 +160,7 @@ func (t *Terminal) Stop() {
        if t.wait {
                t.status = VTDone
        } else {
-               t.status = VTIdle
+               t.Close()
                t.view.Type = t.vtOld
        }
 }
@@ -159,6 +169,13 @@ func (t *Terminal) Stop() {
 // is ready for a new command to execute
 func (t *Terminal) Close() {
        t.status = VTIdle
+       // call the lua function that the user has given as a callback
+       if t.getOutput {
+               _, err := Call(t.callback, t.output.String())
+               if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
+                       TermMessage(err)
+               }
+       }
 }
 
 // WriteString writes a given string to this terminal's pty