pkaramol
pkaramol

Reputation: 19352

Spawn vim using golang

I am trying to run a simple program that spawns a vim process.

The user should be able (when the exec.Command starts) to switch to vim window and the process execution should halt there.

When user closes vim (wq!) the program execution should resume from that point.

The following simple attempt fails but I cannot figure out why

package main

import (
    "log"
    "os/exec"
)

func main() {

    cmd := exec.Command("vim", "lala")

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}
▶ go run main.go
2022/11/25 09:16:44 exit status 1
exit status 1

Why the exit status 1?

Upvotes: 2

Views: 295

Answers (2)

ossan
ossan

Reputation: 1855

You missed these two lines:

cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout

Thanks to these two lines the user is able to edit with vim the file in the terminal. The control is returned to the program when the user quit from the terminal (e.g., with the command :wq). Below, you can find the whole code:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("vim", "lala")

    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout

    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}

Hope this helps!

Upvotes: 2

jabr
jabr

Reputation: 11

Because you should set Stdin and Stdoutfor cmd:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {

    cmd := exec.Command("vim", "lala")
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}

Upvotes: 0

Related Questions