I am writing my own shell and need to implement a history feature where up and down arrow keys show history of commands executed. I need to find out when up and down keys are pressed.
How do i do this?
you want to be capturing input in raw mode. this can get kinda complicated, but here's an example that should get you on the right path:
http://docs.linux.cz/programming/c/unix_examples/raw.html
i'm assuming you're writing your shell in c. if you're using a more high-level language, there might be an easy way to get raw input. in python, for instance, i would use the ncurses module.
Related
As far as I can see, in Konsole both CTRL+ENTER and ENTER look like byte 13 in the stdin of the running app. But when I run mc which obviously uses ncurses lib, pressing CTRL+ENTER inserts the name of the file into the command line while ENTER opens the file. How is it implemented? I tried to look into sources, but they are totally unreadable for me.
mc (midnight commander) doesn't use ncurses for input, but may use it for output. Essentially it is looking for specific character sequences.
mc makes little use of the terminfo database, essentially only to check on the xterm mouse- and alternate-screen features.
In principle, it could read the user-defined capabilities from the ncurses terminfo database (see for example ncurses trapping extended keys (Control-left, Shift-Function etc)), but it does not.
Since you are looking at sources, see the source of mc, in lib/tty/key.c, which contains tables which mc uses as a set of predefined keys. Doing it that way "works" when mc is configured to use slang, for instance, though it has the drawback that it's hardcoded and may not actually match your terminal.
However - as I said, mc does its own input. Further down in key.c, you may see a chunk in get_modifier() ifdef'd with HAVE_TEXTMODE_X11_SUPPORT. Inside that is a call which ultimately goes to XQueryPointer, which mc uses to find the current state of the modifier keys — if it happens to be running in an X display, and if the feature is enabled. You are probably seeing that.
I'm currently in the process of planning out a custom Vim-like editor. It's going to be written in C and I want it to be as portable as possible between as many types of systems as possible.
I'm aware of curses (ncurses, I suppose), the tput command, and how terminals use control sequence (Esc-[ and the CSI character) to change backgrounds, move the cursor, etc.
Of the options above, it seems like ncurses would be the most recommended way of printing for the editor. BUT ncurses also has a LOT of stuff that I rather wouldn't use, and if it's reasonably feasible I'd rather make my own system. I'm not against using it, but .. anyways.
So, my question is: Is there any way to use control sequences in the vast majority of terminals without using a library? Whether through tput or another method?
Thanks!
tput(1) uses the terminfo(5) (or older termcap(5)) database, which provides the mapping from abstract commands such as move cursor to x,y to escape sequences for different terminals. When you run a command such as
$ tput cup 10 3 # move cursor to row/column 10/3
, the terminfo database is queried to find the correct string for your terminal, which is then simply written to stdout. To find the available commands (e.g., cup), look at the cap-name column in terminfo(5). tput determines what terminal you are using by looking at the TERM environment variable.
(This means that you can check what escape characters are being generated by simply doing $ tput [command] > [file] and opening [file] in some editor that can show control characters, which can be handy for exploration. The infocmp(1) command can also be used for this.)
If you use tput (or the underlying tputs(3)), your program is hence automatically portable to different terminals. This is what Vim uses by the way.
However -- in the modern world, pretty much all terminals (or terminal emulators rather) use ANSI escape codes, along with some extensions (see XTerm Control Sequences). I believe the escapes supported by xterm and their behavior have become something of a de facto standard at this point, with other terminal emulators simply copying xterm's behavior. Some text-based UI libraries like termbox seem to do away with support for non-ANSI terminals altogether, and output ANSI escapes directly.
Besides the already-mentioned termbox, there's also S-Lang, which includes a terminal handling component. I believe those are the two most popular "ncurses replacements". I'd give ncurses some time first though.
Open up irb and
type gets. It should work fine.
Then try system("choice /c YN") It should work as expected.
Now try gets again, it behaves oddly.
Can someone tell me why this is?
EDIT: For some clarification on the "odd" behavior, it allows me to type for gets, but doesn't show me the characters and I have to press the enter key twice.
Terminal input-output handling is dark and mysterious art. Anyone trying to make colorized output of bash work in windows PowerShell via ssh knows that. (And various shortcutting habits like Ctrl+Backspace only make things worse.)
One of the possible reasons for your problem is special characters handling. Every terminal out there can type characters in number of different modes, and it parses its own output in search for certain character sequences in order to toggle states.
F.e. here one can find ANSI escape code sequences, one of possible supported standards among different kind of terminals.
See there Esc[5;45m? That will make all the following output to blink on magenta background. And there is significantly more stuff like that out there.
So, the answer to your question taken literally is — your choice command messes something with output modes using special escape sequences, and ruby's gets breaks in that quirk special mode of terminal operation.
But more useful will be the link to HighLine gem documentation. Why one might want to implement platform-specific and obtrusive behavior when it is possible to implement the same with about 12 LOC? All the respect for the Gist goes to botimer, I've only stumbled into his code using search.
I'm trying to determine how the system prints characters to standard input -- that is, how it prints characters which the user can delete and which are considered input if the user hits "Enter."
I happen to be using C, but I would be very surprised if the solution were language-dependent.
Thanks for any insights! : D
As iny says, bash uses readline for its input. The source is available here, and there's a file called complete.c.
To answer your question, I don't think they're actually printed to standard input. Readline contains some kind of buffer for the contents of the line the user is editing, and completion prints into this. When the user presses enter, the contents of the buffer are sent to whatever program wanted to read a line, and in the case of bash, passed along into standard input. (Readline doesn't do this - other programs which use readline might simply store the value into a string for later use.)
Several people have pointed out that bash uses readline, which is true, but I think what you're really asking is how is it able to see what you've typed before you hit enter.
The answer is that ttys (ie: terminals) can be switched into "raw mode", where input processing of the terminal is disabled, and then you'll see every character as it comes in. This also disables automatic echoing of typed characters.
See this guide on Reading a single character from a file or a terminal for more info.
It uses readline library to handle the input and readline provides the history and the completion.
To actually implement completion, access to the keyboard input handling is needed. The completion must be able to modify the buffer used by it. After that it is just about looking at the current input and checking what completions is found. The actual completion logic can work in many ways.
Here's a C snippet that implements tab completion via readline:
http://github.com/rupa/el
Background
Lately I've become a fanatic that everything I type while working on a computer should be compatible with "DRY". If there's anything I have to type more than once in any context, I want some kind of user-aware auto-complete option to do some of the work for me -- always -- no exceptions.
Having to work under Windows, I've looked at GUI solutions to make this insane goal a reality.
The (almost) optimal solution
If you have a moment, open up Firefox 3.0 and type a few keystrokes into the address bar. You will notice that it performs a kind of Incremental Autocomplete based on space-separated sub-strings of whatever you type. Another place in Firefox that does something similar is the about:config URL.
This is sub-optimal, because I don't want this in Firefox only. I want to use this everywhere.
The Question
Does anyone out there know of a widget or app that does nothing but insanely good incremental auto-complete that can be used as a general purpose "run everywhere" tool? Something that allows the user to: 1) maintain one or more "completion candidate files"; 2) pick one of those files as the source for Firefox 3.0 style completion; 3) return the result (or blank if the user canceled), and do those three things only?
Details
Here's how it should work:
STEP1: user saves or more csv file(s) (or other easy-edit format) somewhere in his hard-drive
STEP2: user creates a Windows Script Host script or a batch file (or whatever) instantiates the FilterAsYouType GUI
STEP3: user runs the script file, and the script file instantiates the GUI, telling it which CSV file to use as the source of all potential completions
STEP4: the user either chooses one of the completions, supplies his own text that is not in the list, or cancels out without supplying anything
STEP5: when the user is done the script saves the result to a variable and does something with it
Here is some pseudo-code for the script:
include "GenericTypeaheadWidget";
var gengui = new GenericTypaheadWidget('c:\docs\favorite_foods.csv');
var fave_food = gengui.get_user_input();
if(fave_food != ''){
alert('you chose '+fave_food+'!');
}
The rationale
The goal is to just have a way to always be able to do auto-completions from a list of arbitrary items, even if the list is a couple thousand items, and not have to rely on it being built into some IDE or standalone application that only accepts certain kinds of input or has an overly-complicated API relative to the simplicity of this task.
CSV (or text or sqlite database) would provide a way for me to self-generate "candidate lists" or "history logs" and then just use those logs as the source of the possible completions.
The disclaimer
I've tried several GUI "launcher" programs, command-line engines like power-shell and scripting shells, the regular plain old command-line history with varying degrees of satisfaction. The problem with these is they all do extra superfluous stuff like searching directories or built-in commands. I just want nothing but whatever is in the CSV file I happen to be pointing at.
I'm wondering if there is any simple tool that does nothing but what I'm describing above.
UPDATE: It looks like this question is very closely related to Graphical Command Shell, which captures the essential idea presented here.
You should really try Launchy - it's exactly what you're looking for, a "run anything" with intelligent autocompletion. It completely changes the way you interact with a Windows PC.
And it has open source-code, so you can borrow its autocompletion code if you want to roll your own interface.