1# Linenoise
2
3A minimal, zero-config, BSD licensed, readline replacement used in Redis,
4MongoDB, and Android.
5
6* Single and multi line editing mode with the usual key bindings implemented.
7* History handling.
8* Completion.
9* Hints (suggestions at the right of the prompt as you type).
10* About 1,100 lines of BSD license source code.
11* Only uses a subset of VT100 escapes (ANSI.SYS compatible).
12
13## Can a line editing library be 20k lines of code?
14
15Line editing with some support for history is a really important feature for command line utilities. Instead of retyping almost the same stuff again and again it's just much better to hit the up arrow and edit on syntax errors, or in order to try a slightly different command. But apparently code dealing with terminals is some sort of Black Magic: readline is 30k lines of code, libedit 20k. Is it reasonable to link small utilities to huge libraries just to get a minimal support for line editing?
16
17So what usually happens is either:
18
19 * Large programs with configure scripts disabling line editing if readline is not present in the system, or not supporting it at all since readline is GPL licensed and libedit (the BSD clone) is not as known and available as readline is (Real world example of this problem: Tclsh).
20 * Smaller programs not using a configure script not supporting line editing at all (A problem we had with Redis-cli for instance).
21 
22The result is a pollution of binaries without line editing support.
23
24So I spent more or less two hours doing a reality check resulting in this little library: is it *really* needed for a line editing library to be 20k lines of code? Apparently not, it is possibe to get a very small, zero configuration, trivial to embed library, that solves the problem. Smaller programs will just include this, supporing line editing out of the box. Larger programs may use this little library or just checking with configure if readline/libedit is available and resorting to Linenoise if not.
25
26## Terminals, in 2010.
27
28Apparently almost every terminal you can happen to use today has some kind of support for basic VT100 escape sequences. So I tried to write a lib using just very basic VT100 features. The resulting library appears to work everywhere I tried to use it, and now can work even on ANSI.SYS compatible terminals, since no
29VT220 specific sequences are used anymore.
30
31The library is currently about 1100 lines of code. In order to use it in your project just look at the *example.c* file in the source distribution, it is trivial. Linenoise is BSD code, so you can use both in free software and commercial software.
32
33## Tested with...
34
35 * Linux text only console ($TERM = linux)
36 * Linux KDE terminal application ($TERM = xterm)
37 * Linux xterm ($TERM = xterm)
38 * Linux Buildroot ($TERM = vt100)
39 * Mac OS X iTerm ($TERM = xterm)
40 * Mac OS X default Terminal.app ($TERM = xterm)
41 * OpenBSD 4.5 through an OSX Terminal.app ($TERM = screen)
42 * IBM AIX 6.1
43 * FreeBSD xterm ($TERM = xterm)
44 * ANSI.SYS
45 * Emacs comint mode ($TERM = dumb)
46
47Please test it everywhere you can and report back!
48
49## Let's push this forward!
50
51Patches should be provided in the respect of Linenoise sensibility for small
52easy to understand code.
53
54Send feedbacks to antirez at gmail
55
56# The API
57
58Linenoise is very easy to use, and reading the example shipped with the
59library should get you up to speed ASAP. Here is a list of API calls
60and how to use them.
61
62    char *linenoise(const char *prompt);
63
64This is the main Linenoise call: it shows the user a prompt with line editing
65and history capabilities. The prompt you specify is used as a prompt, that is,
66it will be printed to the left of the cursor. The library returns a buffer
67with the line composed by the user, or NULL on end of file or when there
68is an out of memory condition.
69
70When a tty is detected (the user is actually typing into a terminal session)
71the maximum editable line length is `LINENOISE_MAX_LINE`. When instead the
72standard input is not a tty, which happens every time you redirect a file
73to a program, or use it in an Unix pipeline, there are no limits to the
74length of the line that can be returned.
75
76The returned line should be freed with the `free()` standard system call.
77However sometimes it could happen that your program uses a different dynamic
78allocation library, so you may also used `linenoiseFree` to make sure the
79line is freed with the same allocator it was created.
80
81The canonical loop used by a program using Linenoise will be something like
82this:
83
84    while((line = linenoise("hello> ")) != NULL) {
85        printf("You wrote: %s\n", line);
86        linenoiseFree(line); /* Or just free(line) if you use libc malloc. */
87    }
88
89## Single line VS multi line editing
90
91By default, Linenoise uses single line editing, that is, a single row on the
92screen will be used, and as the user types more, the text will scroll towards
93left to make room. This works if your program is one where the user is
94unlikely to write a lot of text, otherwise multi line editing, where multiple
95screens rows are used, can be a lot more comfortable.
96
97In order to enable multi line editing use the following API call:
98
99    linenoiseSetMultiLine(1);
100
101You can disable it using `0` as argument.
102
103## History
104
105Linenoise supporst history, so that the user does not have to retype
106again and again the same things, but can use the down and up arrows in order
107to search and re-edit already inserted lines of text.
108
109The followings are the history API calls:
110
111    int linenoiseHistoryAdd(const char *line);
112    int linenoiseHistorySetMaxLen(int len);
113    int linenoiseHistorySave(const char *filename);
114    int linenoiseHistoryLoad(const char *filename);
115
116Use `linenoiseHistoryAdd` every time you want to add a new element
117to the top of the history (it will be the first the user will see when
118using the up arrow).
119
120Note that for history to work, you have to set a length for the history
121(which is zero by default, so history will be disabled if you don't set
122a proper one). This is accomplished using the `linenoiseHistorySetMaxLen`
123function.
124
125Linenoise has direct support for persisting the history into an history
126file. The functions `linenoiseHistorySave` and `linenoiseHistoryLoad` do
127just that. Both functions return -1 on error and 0 on success.
128
129## Completion
130
131Linenoise supports completion, which is the ability to complete the user
132input when she or he presses the `<TAB>` key.
133
134In order to use completion, you need to register a completion callback, which
135is called every time the user presses `<TAB>`. Your callback will return a
136list of items that are completions for the current string.
137
138The following is an example of registering a completion callback:
139
140    linenoiseSetCompletionCallback(completion);
141
142The completion must be a function returning `void` and getting as input
143a `const char` pointer, which is the line the user has typed so far, and
144a `linenoiseCompletions` object pointer, which is used as argument of
145`linenoiseAddCompletion` in order to add completions inside the callback.
146An example will make it more clear:
147
148    void completion(const char *buf, linenoiseCompletions *lc) {
149        if (buf[0] == 'h') {
150            linenoiseAddCompletion(lc,"hello");
151            linenoiseAddCompletion(lc,"hello there");
152        }
153    }
154
155Basically in your completion callback, you inspect the input, and return
156a list of items that are good completions by using `linenoiseAddCompletion`.
157
158If you want to test the completion feature, compile the example program
159with `make`, run it, type `h` and press `<TAB>`.
160
161## Hints
162
163Linenoise has a feature called *hints* which is very useful when you
164use Linenoise in order to implement a REPL (Read Eval Print Loop) for
165a program that accepts commands and arguments, but may also be useful in
166other conditions.
167
168The feature shows, on the right of the cursor, as the user types, hints that
169may be useful. The hints can be displayed using a different color compared
170to the color the user is typing, and can also be bold.
171
172For example as the user starts to type `"git remote add"`, with hints it's
173possible to show on the right of the prompt a string `<name> <url>`.
174
175The feature works similarly to the history feature, using a callback.
176To register the callback we use:
177
178    linenoiseSetHintsCallback(hints);
179
180The callback itself is implemented like this:
181
182    char *hints(const char *buf, int *color, int *bold) {
183        if (!strcasecmp(buf,"git remote add")) {
184            *color = 35;
185            *bold = 0;
186            return " <name> <url>";
187        }
188        return NULL;
189    }
190
191The callback function returns the string that should be displayed or NULL
192if no hint is available for the text the user currently typed. The returned
193string will be trimmed as needed depending on the number of columns available
194on the screen.
195
196It is possible to return a string allocated in dynamic way, by also registering
197a function to deallocate the hint string once used:
198
199    void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *);
200
201The free hint callback will just receive the pointer and free the string
202as needed (depending on how the hits callback allocated it).
203
204As you can see in the example above, a `color` (in xterm color terminal codes)
205can be provided together with a `bold` attribute. If no color is set, the
206current terminal foreground color is used. If no bold attribute is set,
207non-bold text is printed.
208
209Color codes are:
210
211    red = 31
212    green = 32
213    yellow = 33
214    blue = 34
215    zircon = 35
216    cyan = 36
217    white = 37;
218
219## Screen handling
220
221Sometimes you may want to clear the screen as a result of something the
222user typed. You can do this by calling the following function:
223
224    void linenoiseClearScreen(void);
225