realtime: implement the `prompt` service
[nit.git] / lib / readline.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2016 Frédéric Vachon <fredvac@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # GNU readline library wrapper
18 module readline is ldflags "-lreadline"
19
20 import prompt
21
22 in "C" `{
23 #include <readline/readline.h>
24 #include <readline/history.h>
25 `}
26
27 private fun native_readline(prompt: CString): CString `{
28 return readline(prompt);
29 `}
30
31 private fun native_add_history(data: CString) `{
32 if (data == NULL) return;
33 add_history(data);
34 `}
35
36 # Set emacs keybindings mode
37 fun set_vi_mode `{ rl_editing_mode = 0; `}
38
39 # Set emacs keybindings mode
40 fun set_emacs_mode `{ rl_editing_mode = 1; `}
41
42 # Use the GNU Library readline function
43 # Returns `null` if EOF is read
44 # If `with_history` is true, it will save all commands in the history except
45 # empty strings and white characters strings
46 fun readline(message: String, with_history: nullable Bool): nullable String do
47 var line = native_readline(message.to_cstring)
48 if line.address_is_null then return null
49
50 var nit_str = line.to_s
51
52 if with_history != null and with_history then
53 if nit_str.trim != "" then native_add_history(line)
54 end
55
56 return nit_str
57 end
58
59 # Adds the data String to the history no matter what it contains
60 fun add_history(data: String) do native_add_history data.to_cstring
61
62 redef fun prompt(prompt, add_history) do return readline(prompt.to_s, add_history)
63
64 redef fun prompt_add_history(line) do native_add_history(line.to_cstring)