Merge: Added contributing guidelines and link from readme
[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 in "C" `{
21 #include <readline/readline.h>
22 #include <readline/history.h>
23 `}
24
25 private fun native_readline(prompt: NativeString): NativeString `{
26 return readline(prompt);
27 `}
28
29 private fun native_add_history(data: NativeString) `{
30 if (data == NULL) return;
31 add_history(data);
32 `}
33
34 # Set emacs keybindings mode
35 fun set_vi_mode `{ rl_editing_mode = 0; `}
36
37 # Set emacs keybindings mode
38 fun set_emacs_mode `{ rl_editing_mode = 1; `}
39
40 # Use the GNU Library readline function
41 # Returns `null` if EOF is read
42 # If `with_history` is true, it will save all commands in the history except
43 # empty strings and white characters strings
44 fun readline(message: String, with_history: nullable Bool): nullable String do
45 var line = native_readline(message.to_cstring)
46 if line.address_is_null then return null
47
48 var nit_str = line.to_s
49
50 if with_history != null and with_history then
51 if nit_str.trim != "" then native_add_history(line)
52 end
53
54 return nit_str
55 end
56
57 # Adds the data String to the history no matter what it contains
58 fun add_history(data: String) do native_add_history data.to_cstring