Making a full screen Terminal application with Go
Asked Answered
U

3

5

I'm trying to build a full screen terminal application. I'm using Go as my language of choice. I've figured out how to read from os.Stdin, but I'm unclear on how to clear the terminal window and manipulate the cursor position. I also want to capture the terminal input without it being printed (echoed back).

My questions are:

  1. How can I effectively clear and print to the terminal with column/row coordinates?
  2. How do I stop the terminal from printing keys pressed

My intent:

I want to create a full screen terminal application that renders it's own UI and handles input internally (hot keys/navigation/etc...).

If there are any libraries that cover this sort of use case please feel free to suggest them.

Unroot answered 2/9, 2015 at 22:36 Comment(2)
You're looking for: github.com/nsf/termbox-goSeminal
@TimCooper Much appreciated tim :)Unroot
A
6

The easiest way to clear the terminal and set position is via ansi escape codes. However, this may not be the ideal way as variation in terminals may come back to bite you.

fmt.Print("\033[2J") //Clear screen
fmt.Printf("\033[%d;%dH", line, col) // Set cursor position

A better alternative would be to use a library like goncurses or termbox-go (credit: second is from Tim Cooper's comment).

With such a library you can do things like this:

import (
    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        panic(err)
    }
    defer gc.End()
    s.Move(5, 2)
    s.Println("Hello")
    s.GetChar()
}

Code above copied from Rosetta Code

Admeasure answered 2/9, 2015 at 22:39 Comment(0)
F
4

As of December 2019, I would recommend using rivo/tview library.

(goncurses mentioned by @vastlysuperiorman has not been updated since June 2019 and termbox-go is explicitly declared unmaintained).


Here's the "hello world" app, taken from the project's README (reformatted for readability):

package main

import (
    "github.com/rivo/tview"
)

func main() {

    box := tview.NewBox().
        SetBorder(true).
        SetTitle("Hello, world!")

    if err := tview.NewApplication().SetRoot(box, true).Run(); err != nil {
        panic(err)
    }
}


tview provides screenshots and example code as well as the standard godoc reference.

Febri answered 26/12, 2019 at 7:52 Comment(0)
S
0

To stop the terminal from printing keys pressed you can use the below code:

    import (
        "fmt"
        "syscall"
        "golang.org/x/crypto/ssh/terminal"
    )

    func main(){
        fmt.Print("Enter Value: ")
        byteInput, _ := terminal.ReadPassword(int(syscall.Stdin))
        input:= string(byteInput)
        fmt.Println() // it's necessary to add a new line after user's input
        fmt.Printf("Your input is '%s'", input)
    }
Spotless answered 1/8, 2019 at 20:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.