Search code examples
shellgocommand-line-interfacettystty

Making a full screen Terminal application with Go


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.


Solution

  • 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