41

Is there a Go function similar to C's getchar able to handle tab press in console? I want to make some sort of completion in my console app.

Dave C
  • 7,729
  • 4
  • 49
  • 65
demi
  • 5,384
  • 6
  • 37
  • 57
  • 1
    Found a good example for rolling your own: https://github.com/SimonWaldherr/golang-examples/blob/master/advanced/getchar.go – mtso Jan 09 '17 at 21:54

6 Answers6

25

C's getchar() example:

#include <stdio.h>
void main()
{
    char ch;
    ch = getchar();
    printf("Input Char Is :%c",ch);
}

Go equivalent:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

    fmt.Printf("Input Char Is : %v", string([]byte(input)[0]))

    // fmt.Printf("You entered: %v", []byte(input))
}

The last commented line just shows that when you press tab the first element is U+0009 ('CHARACTER TABULATION').

However for your needs (detecting tab) C's getchar() is not suitable as it requires the user to hit enter. What you need is something like ncurses' getch()/ readline/ jLine as mentioned by @miku. With these, you actually wait for a single keystroke.

So you have multiple options:

  1. Use ncurses / readline binding, for example https://code.google.com/p/goncurses/ or equivalent like https://github.com/nsf/termbox

  2. Roll your own see http://play.golang.org/p/plwBIIYiqG for starting point

  3. use os.Exec to run stty or jLine.

refs:

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/zhBE5MH4n-Q

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/S9AO_kHktiY

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/icMfYF8wJCk

rputikar
  • 1,523
  • 13
  • 14
17

Assuming that you want unbuffered input (without having to hit enter), this does the job on UNIX systems:

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    // disable input buffering
    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    // do not display entered characters on the screen
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    // restore the echoing state when exiting
    defer exec.Command("stty", "-F", "/dev/tty", "echo").Run()

    var b []byte = make([]byte, 1)
    for {
        os.Stdin.Read(b)
        fmt.Println("I got the byte", b, "("+string(b)+")")
    }
}
blinry
  • 4,746
  • 4
  • 26
  • 31
  • 8
    This leaves the terminal in a non-echoing state after exit. Adding `defer exec.Command("stty", "-F", "/dev/tty", "echo")` fixes that. – Grumdrig Mar 18 '14 at 20:00
  • 2
    defer exec.Command("stty", "-F", "/dev/tty", "echo").Run() doesn't work for me, I have to type 'reset' :( – gdonald Feb 11 '15 at 23:25
  • 5
    Don't do massively inefficient, error prone, non-portable, etc exec of stty when you can just use [`terminal.MakeRaw`](https://godoc.org/golang.org/x/crypto/ssh/terminal#MakeRaw) from `golang.org/x/crypto/ssh/terminal`. – Dave C Aug 07 '19 at 14:46
  • If the defer "isn't working", actually build and compile the project to run it, instead of doing go run *.go. This worked for me. – Aaron Nov 07 '21 at 15:12
9

Other answers here suggest such things as:

  • Using cgo

  • os.Exec of stty

    • not portable
    • inefficient
    • error prone
  • using code that uses /dev/tty

    • not portable
  • using a GNU readline package

    • inefficient if it's a wrapper to C readline or if implemented using one of the above techniques
    • otherwise okay

However, for the simple case this is easy just using a package from the Go Project's Sub-repositories.

[Edit: Previously this answer used the golang.org/x/crypto/ssh/terminal package which has since been deprecated; it was moved to golang.org/x/term. Code/links updated appropriately.]

Basically, use term.MakeRaw and term.Restore to set standard input to raw mode (checking for errors, e.g. if stdin is not a terminal); then you can either read bytes directly from os.Stdin, or more likely, via a bufio.Reader (for better efficiency).

For example, something like this:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"

    "golang.org/x/term"
)

func main() {
    // fd 0 is stdin
    state, err := term.MakeRaw(0)
    if err != nil {
        log.Fatalln("setting stdin to raw:", err)
    }
    defer func() {
        if err := term.Restore(0, state); err != nil {
            log.Println("warning, failed to restore terminal:", err)
        }
    }()

    in := bufio.NewReader(os.Stdin)
    for {
        r, _, err := in.ReadRune()
        if err != nil {
            log.Println("stdin:", err)
            break
        }
        fmt.Printf("read rune %q\r\n", r)
        if r == 'q' {
            break
        }
    }
}
Dave C
  • 7,729
  • 4
  • 49
  • 65
8

Thanks goes to Paul Rademacher - this works (at least on Mac):

package main

import (
    "bytes"
    "fmt"

    "github.com/pkg/term"
)

func getch() []byte {
    t, _ := term.Open("/dev/tty")
    term.RawMode(t)
    bytes := make([]byte, 3)
    numRead, err := t.Read(bytes)
    t.Restore()
    t.Close()
    if err != nil {
        return nil
    }
    return bytes[0:numRead]
}

func main() {
    for {
        c := getch()
        switch {
        case bytes.Equal(c, []byte{3}):
            return
        case bytes.Equal(c, []byte{27, 91, 68}): // left
            fmt.Println("LEFT pressed")
        default:
            fmt.Println("Unknown pressed", c)
        }
    }
    return
}
Slava V
  • 16,686
  • 14
  • 60
  • 63
  • 1
    Works perfectly on Linux also – hookenz Jan 08 '18 at 20:02
  • 2
    Using `/dev/tty` is non-portable. *Never* ignore errors! Don't flip the terminal in/out of raw mode for each "character", don't re-open "/dev/tty" for each "character". This doesn't actually get characters but up to three bytes. – Dave C Aug 07 '19 at 15:13
1

1- You may use C.getch():

This works in Windows command line, Reads only one character without Enter:
(Run output binary file inside shell (terminal), not inside pipe or Editor.)

package main

//#include<conio.h>
import "C"

import "fmt"

func main() {
    c := C.getch()
    fmt.Println(c)
}

2- For Linux ( tested on Ubuntu ):

package main

/*
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
char getch(){
    char ch = 0;
    struct termios old = {0};
    fflush(stdout);
    if( tcgetattr(0, &old) < 0 ) perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if( tcsetattr(0, TCSANOW, &old) < 0 ) perror("tcsetattr ICANON");
    if( read(0, &ch,1) < 0 ) perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0) perror("tcsetattr ~ICANON");
    return ch;
}
*/
import "C"

import "fmt"

func main() {
    fmt.Println(C.getch())
    fmt.Println()
}

See:
What is Equivalent to getch() & getche() in Linux?
Why can't I find <conio.h> on Linux?


3- Also this works, but needs "Enter":

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    r := bufio.NewReader(os.Stdin)
    c, err := r.ReadByte()
    if err != nil {
        panic(err)
    }
    fmt.Println(c)
}
Community
  • 1
  • 1
  • Still need to hit enter for me on openSUSE Leap 42.1 . :( – lfree Aug 25 '16 at 09:01
  • Sorry I forgot to mention that `conio.h` is windows only! I have tried [this](http://stackoverflow.com/questions/8792317/why-cant-i-find-conio-h-on-linux) and [this](http://stackoverflow.com/questions/9541679/undefined-reference-to-stdscr), it's able to run but the getch() always return -1. – lfree Aug 26 '16 at 02:38
  • Finally, I take @blinry 's method. – lfree Aug 26 '16 at 02:39
  • @lfree: See new Edit for Linux ( 2), I hope this helps. –  Sep 13 '16 at 10:05
  • 1
    The second method works on openSUSE Leap42.1. Thank you very much! :) – lfree Sep 22 '16 at 07:21
  • the linux version actually only works with a terminal as stdin, not with a pipe – hoijui May 15 '20 at 18:43
  • When trying to build/run the linux version, it complains: could not determine kind of name for C.getch – PePa Apr 11 '21 at 05:14
-5

You can also use ReadRune:

reader := bufio.NewReader(os.Stdin)
// ...
char, _, err := reader.ReadRune()
if err != nil {
    fmt.Println("Error reading key...", err)
}

A rune is similar to a character, as GoLang does not really have characters, in order to try and support multiple languages/unicode/etc.

Another Prog
  • 841
  • 13
  • 19
  • 1
    ReadRune reads one character at a time, but it is triggered only when pressing enter in a console; this is why this doesn't solve the OP's issue. (I wondered why you didn't have more upvotes, and just tried it :) ) – Christian Rondeau Sep 17 '17 at 00:45