use crate::banner;
use nu_ansi_term::Color;
use reedline::{
default_emacs_keybindings, ColumnarMenu, Completer, Emacs, FileBackedHistory, KeyCode,
KeyModifiers, MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu, Signal, Span, Suggestion,
};
use reedline::{DefaultPrompt, DefaultPromptSegment};
fn history_path() -> std::path::PathBuf {
let dir = std::env::var_os("HOME")
.map(|h| std::path::PathBuf::from(h).join(".pythonrs"))
.unwrap_or_else(|| std::path::PathBuf::from(".pythonrs"));
let _ = std::fs::create_dir_all(&dir);
dir.join("history")
}
fn build_static_words() -> Vec<String> {
let mut v: Vec<String> = crate::lsp::corpus()
.iter()
.map(|(name, ..)| (*name).to_string())
.collect();
v.sort();
v.dedup();
v
}
fn completion_word_start(line: &str, pos: usize) -> (usize, &str) {
let pos = pos.min(line.len());
let before = line.get(..pos).unwrap_or("");
let start = before
.char_indices()
.rev()
.find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
(start, line.get(start..pos).unwrap_or(""))
}
fn attr_context(line: &str, pos: usize) -> Option<(&str, usize, &str)> {
let (pstart, partial) = completion_word_start(line, pos);
let before = line.get(..pstart)?;
if !before.ends_with('.') {
return None;
}
let dot = pstart - 1;
let base_before = line.get(..dot)?;
let base_start = base_before
.char_indices()
.rev()
.find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
let base = line.get(base_start..dot)?;
if base.is_empty() {
return None;
}
Some((base, pstart, partial))
}
fn corpus_chapter_names(chapter: &str) -> Vec<String> {
crate::lsp::corpus()
.iter()
.filter(|(_, ch, ..)| *ch == chapter)
.map(|(name, ..)| (*name).to_string())
.collect()
}
fn suggestion(value: String, span: Span) -> Suggestion {
Suggestion {
value,
description: None,
style: None,
extra: None,
span,
append_whitespace: false,
display_override: None,
match_indices: None,
}
}
struct PyCompleter {
static_words: Vec<String>,
}
impl Completer for PyCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
if let Some((base, start, partial)) = attr_context(line, pos) {
let candidates: Option<Vec<String>> = crate::host::with_host(|h| {
h.attr_completions(base).map(|a| match a {
crate::host::AttrCompletion::BuiltinType(ch) => corpus_chapter_names(ch),
crate::host::AttrCompletion::Names(v) => v,
})
});
if let Some(mut names) = candidates {
let span = Span::new(start, pos);
names.retain(|w| w.starts_with(partial));
names.sort();
names.dedup();
return names.into_iter().map(|w| suggestion(w, span)).collect();
}
}
let (start, prefix) = completion_word_start(line, pos);
let span = Span::new(start, pos);
let dynamic = crate::host::with_host(|h| h.global_names());
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
let mut out: Vec<Suggestion> = Vec::new();
for w in self.static_words.iter().chain(dynamic.iter()) {
if !w.starts_with(prefix) {
continue;
}
if !seen.insert(w.as_str()) {
continue;
}
out.push(suggestion(w.clone(), span));
}
out.sort_by(|a, b| a.value.cmp(&b.value));
out
}
}
fn build_editor() -> Reedline {
let completer = PyCompleter {
static_words: build_static_words(),
};
let menu = ColumnarMenu::default()
.with_name("completion_menu")
.with_columns(4)
.with_column_padding(2);
let mut keybindings = default_emacs_keybindings();
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("completion_menu".to_string()),
ReedlineEvent::MenuNext,
]),
);
keybindings.add_binding(
KeyModifiers::SHIFT,
KeyCode::BackTab,
ReedlineEvent::MenuPrevious,
);
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::BackTab,
ReedlineEvent::MenuPrevious,
);
let editor = Reedline::create()
.with_completer(Box::new(completer))
.with_menu(ReedlineMenu::EngineCompleter(Box::new(menu)))
.with_edit_mode(Box::new(Emacs::new(keybindings)));
match FileBackedHistory::with_file(5_000, history_path()) {
Ok(h) => editor.with_history(Box::new(h)),
Err(_) => editor,
}
}
pub fn run() {
banner::print_banner();
crate::host::reset_host();
let mut line_editor = build_editor();
let prompt = DefaultPrompt::new(
DefaultPromptSegment::Basic(">>> ".to_string()),
DefaultPromptSegment::Empty,
);
loop {
match line_editor.read_line(&prompt) {
Ok(Signal::Success(mut buffer)) => {
if buffer.trim().is_empty() {
continue;
}
if opens_block(&buffer) {
let cont_prompt = DefaultPrompt::new(
DefaultPromptSegment::Basic("... ".to_string()),
DefaultPromptSegment::Empty,
);
while let Ok(Signal::Success(more)) = line_editor.read_line(&cont_prompt) {
if more.trim().is_empty() {
break;
}
buffer.push('\n');
buffer.push_str(&more);
}
}
run_line(&buffer);
}
Ok(Signal::CtrlC) => continue,
Ok(Signal::CtrlD) => break,
Ok(_) => continue,
Err(_) => break,
}
}
}
pub fn run_piped() {
use std::io::BufRead;
crate::host::reset_host();
let stdin = std::io::stdin();
let mut lines = stdin.lock().lines().map_while(Result::ok);
while let Some(mut buffer) = lines.next() {
if buffer.trim().is_empty() {
continue;
}
if opens_block(&buffer) {
for more in lines.by_ref() {
if more.trim().is_empty() {
break;
}
buffer.push('\n');
buffer.push_str(&more);
}
}
run_line(&buffer);
}
}
fn opens_block(s: &str) -> bool {
let t = s.trim_end();
t.ends_with(':')
|| t.ends_with('\\')
|| t.ends_with('(')
|| t.ends_with('[')
|| t.ends_with('{')
}
fn run_line(src: &str) {
match crate::compile_interactive(src) {
Ok(prog) => match crate::run_compiled(prog) {
Ok(_) => {}
Err(e) => eprintln!("{}", Color::Red.paint(crate::plain_error(e))),
},
Err(e) => eprint!(
"{}",
Color::Red.paint(crate::render_compile_error(&e, src, "<stdin>"))
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn static_words_include_keywords_builtins_methods() {
let v = build_static_words();
assert!(v.iter().any(|w| w == "def"), "keyword `def` missing");
assert!(v.iter().any(|w| w == "lambda"), "keyword `lambda` missing");
assert!(v.iter().any(|w| w == "sqrt"), "math `sqrt` missing");
assert!(
v.iter().any(|w| w == "append"),
"list method `append` missing"
);
}
#[test]
fn word_start_at_bare_identifier() {
let s = "print(le";
let (st, pre) = completion_word_start(s, s.len());
assert_eq!(st, 6);
assert_eq!(pre, "le");
}
#[test]
fn word_start_snaps_after_dot() {
let s = "math.sq";
let (st, pre) = completion_word_start(s, s.len());
assert_eq!(st, 5);
assert_eq!(pre, "sq");
}
#[test]
fn word_start_empty_prefix_after_space() {
let s = "x = ";
let (st, pre) = completion_word_start(s, s.len());
assert_eq!(st, 4);
assert_eq!(pre, "");
}
#[test]
fn attr_context_detects_receiver_and_partial() {
assert_eq!(attr_context("s.up", 4), Some(("s", 2, "up")));
assert_eq!(attr_context("s.", 2), Some(("s", 2, "")));
assert_eq!(attr_context("upp", 3), None);
assert_eq!(attr_context("a.b.c", 5), Some(("b", 4, "c")));
}
#[test]
fn attr_completion_str_offers_str_methods_only() {
use fusevm::Value;
use std::sync::Arc;
crate::host::reset_host();
crate::host::with_host(|h| h.set_global("s", Value::Str(Arc::new("hi".to_string()))));
let mut c = PyCompleter {
static_words: build_static_words(),
};
let line = "s.up";
let out = c.complete(line, line.len());
assert!(
out.iter().any(|s| s.value == "upper"),
"str.upper not offered"
);
assert!(out.iter().all(|s| s.value.starts_with("up")));
let all = c.complete("s.", 2);
assert!(all.iter().any(|s| s.value == "split"), "str.split missing");
assert!(
!all.iter().any(|s| s.value == "keys"),
"dict.keys leaked onto str"
);
}
#[test]
fn attr_completion_list_offers_list_methods() {
crate::host::reset_host();
let lst = crate::host::with_host(|h| h.new_list(Vec::new()));
crate::host::with_host(|h| h.set_global("xs", lst));
let mut c = PyCompleter {
static_words: build_static_words(),
};
let out = c.complete("xs.app", 6);
assert!(
out.iter().any(|s| s.value == "append"),
"list.append not offered"
);
assert!(out.iter().all(|s| s.value.starts_with("app")));
}
#[test]
fn attr_completion_unbound_base_falls_back_to_words() {
crate::host::reset_host();
let mut c = PyCompleter {
static_words: build_static_words(),
};
let out = c.complete("nope.up", 7);
assert!(out.iter().all(|s| s.value.starts_with("up")));
}
#[test]
fn completer_prefix_matches_and_dedups() {
let mut c = PyCompleter {
static_words: build_static_words(),
};
let line = "le";
let out = c.complete(line, line.len());
assert!(
out.iter().any(|s| s.value == "len"),
"`len` not suggested for `le`"
);
assert!(out.iter().all(|s| s.value.starts_with("le")));
let mut vals: Vec<&str> = out.iter().map(|s| s.value.as_str()).collect();
vals.sort();
let n = vals.len();
vals.dedup();
assert_eq!(n, vals.len(), "duplicate suggestions leaked");
}
}