0

Programs like Emacs and Nano can run in a terminal window and accept real time user input, how might I accomplish this myself? I am looking to use C++ but I can see this could require interfacing with the user's shell, in this case Bash. How can I take input (be it from the mouse or keyboard) from the terminal window without the user having to press enter?

My target platform is Mac OSX Version 10.13.5, but answers on how to do this on other platforms like Windows or Linux are also welcome.

Shades
  • 667
  • 1
  • 7
  • 22
  • 1
    Both those editors are open source. If you wonder how they do this or that, you can simply browse the source code. – SergeyA Aug 15 '18 at 18:23
  • @SergeyA The source code of these programs is MASSIVE. I have the code for nano right in front of me and it's hundreds and hundreds of C and header files. Emacs would be even more complicated. I understand that eventually I might be able to find it, but it would take a very long time, and really, it's more work than it needs to be. I am only asking if anybody has a method of doing this type of thing. – Shades Aug 15 '18 at 18:25
  • 1
    You'll need to use platform-specific commands like [`GetAsyncKeyState`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx) on Windows, or a library like [ncurses](http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html). – 0x5453 Aug 15 '18 at 18:27
  • @0x5453 Any Bash commands that might do it? Ncurses might be a sledgehammer to crack a peanut in this case. – Shades Aug 15 '18 at 18:28
  • @Shades the fact that you keep talking about bash command clearly indicates that you are not ready to tackle this question. I seriously suggest you look at the source code (nano is not that big at all, actually). And it does use ncurses, by the way. – SergeyA Aug 15 '18 at 18:32
  • https://stackoverflow.com/questions/22832933/what-does-stty-raw-echo-do-on-os-x – stark Aug 15 '18 at 18:34
  • @SergeyA I was merely hoping there might be a way to do this without big libraries. I am new to Bash scripting but I am not new to C++. I didn't mean to upset you. – Shades Aug 15 '18 at 18:41
  • emacs is essentially a ***termcap*** application (not ***curses***). By the way, this is a duplicate... – Thomas Dickey Aug 15 '18 at 18:45
  • BTW, Emacs is written in LISP and doesn't have anything to do with C++. – Thomas Matthews Aug 15 '18 at 18:47

1 Answers1

4

These programs set the terminal to raw mode as opposed to cooked mode. Cooked mode is read a line at a time and is handled by the terminal driver, and raw mode is read a character at a time and is handled by the running program instead.

This Answer has more information.

This Repo is a simple project that implements this mode that you can learn from. man termios will also give you information about manipulating terminal modes.

Major
  • 544
  • 4
  • 19