1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#![crate_name="linenoise"]
#![crate_type="lib"]

//! This is a library that interfaces with the linenoise library.
//! [Linenoise](https://github.com/antirez/linenoise) is a library implemented by Antirez, the Redis creator as a
//! replacement for readline.
//!
//! This library is just a binding to this library.
//!
//! ```rust
//! extern crate linenoise;
//! fn callback(input: &str) -> Vec<String> {
//!   let mut ret : Vec<&str>;
//!    if input.starts_with("s") {
//!     ret = vec!["suggestion", "suggestion2", "suggestion-three"];
//!   } else {
//!     ret = vec!["wot"];
//!   }
//!
//!     return ret.iter().map(|s| s.to_string()).collect();
//! }
//!
//! fn main() {
//!   linenoise::set_callback(callback);
//!
//!     loop {
//!       let val = linenoise::input("hello > ");
//!         match val {
//!             None => { break }
//!             Some(input) => {
//!                 println!("> {}", input);
//!                 linenoise::history_add(input.as_slice());
//!                 if input.as_slice() == "clear" {
//!                   linenoise::clear_screen();
//!                 }
//!             }
//!         }
//!     }
//! }
//! ```


extern crate libc;

use std::ffi::CString;
use std::ffi::CStr;
use std::str;

pub mod ffi;


pub type Completions = ffi::Struct_linenoiseCompletions;
type Callback = ffi::linenoiseCompletionCallback;

pub type CompletionCallback = fn(&str) -> Vec<String>;
static mut USER_COMPLETION: Option<CompletionCallback> = None;


/// Sets the callback when tab is pressed
pub fn set_callback(rust_cb: CompletionCallback ) {
    unsafe {
        USER_COMPLETION = Some(rust_cb);
        let ca = internal_callback as *mut _;
        ffi::linenoiseSetCompletionCallback(ca);
    }
}

/// Shows the prompt with your prompt as prefix
/// Retuns the typed string or None is nothing or EOF
pub fn input(prompt: &str) -> Option<String> {
    let cprompt = CString::new(prompt.as_bytes()).unwrap();

    unsafe {
        let cs = cprompt.as_ptr();
        let rret = ffi::linenoise(cs);

        let rval = if rret != 0 as *mut i8 {
            let ptr = rret as *const i8;
            let cast = str::from_utf8(CStr::from_ptr(ptr).to_bytes()).unwrap().to_string();
            libc::free(ptr as *mut libc::c_void);
            Some(cast)
        } else {
            None
        };
        return rval;
    }
}

/// Add this string to the history
pub fn history_add(line: &str) -> i32 {
    let cs = CString::new(line).unwrap().as_ptr();
    let ret: i32;
    unsafe {
        ret = ffi::linenoiseHistoryAdd(cs);
    }
    ret
}

/// Set max length history
pub fn history_set_max_len(len: i32) -> i32 {
    let ret: i32;
    unsafe {
        ret = ffi::linenoiseHistorySetMaxLen(len);
    }
    ret
}

/// Save the history on disk
pub fn history_save(file: &str) -> i32 {
    let fname = CString::new(file).unwrap().as_ptr();
    let ret: i32;
    unsafe {
        ret = ffi::linenoiseHistorySave(fname);
    }
    ret
}

/// Load the history on disk
pub fn history_load(file: &str) -> i32 {
    let fname = CString::new(file).unwrap().as_ptr();
    let ret: i32;
    unsafe {
        ret = ffi::linenoiseHistoryLoad(fname);
    }
    ret
}

/// Get a line from the history by (zero-based) index
pub fn history_line(index: i32) -> Option<String> {
    unsafe {
        let ret = ffi::linenoiseHistoryLine(index);
        let rval = if ret != 0 as *mut i8 {
            let ptr = ret as *const i8;
            let cast = str::from_utf8(CStr::from_ptr(ptr).to_bytes()).unwrap().to_string();
            libc::free(ptr as *mut libc::c_void);
            Some(cast)
        } else {
            None
        };
        return rval;
    }
}

///Clears the screen
pub fn clear_screen() {
    unsafe {
        ffi::linenoiseClearScreen();
    }
}

pub fn set_multiline(ml: i32) {
    unsafe {
        ffi::linenoiseSetMultiLine(ml);
    }
}

pub fn print_key_codes() {
    unsafe {
        ffi::linenoisePrintKeyCodes();
    }
}


/// Add a completion to the current list of completions.
pub fn add_completion(c: *mut Completions, s: &str) {
    unsafe {
        ffi::linenoiseAddCompletion(c, CString::new(s).unwrap().as_ptr());
    }
}

fn internal_callback(cs: *mut libc::c_char, lc:*mut Completions ) {
    unsafe {
        (*lc).len = 0;
    }
    let cr = cs as *const _;


    unsafe {
        let input = str::from_utf8(CStr::from_ptr(cr).to_bytes()).unwrap();
        for external_callback in USER_COMPLETION.iter() {
            let ret = (*external_callback)(input);
            for x in ret.iter() {
                add_completion(lc, x.as_ref());
            }
        }
    }
}