kkawakam / rustyline

Readline Implementation in Rust
https://crates.io/crates/rustyline/
MIT License
1.52k stars 175 forks source link

Thoughts on making KeyEvent accessible to ValidationContext? #730

Closed luketpeterson closed 11 months ago

luketpeterson commented 11 months ago

I'm trying to implement a more specialized version of Cmd::AcceptOrInsertLine.accept_in_the_middle that would behave differently for different keys.

I'm wondering if there are any objections to plumbing through a path to get the KeyEvent that triggered the Accept, into the ValidationContext. This accessor could return None if the accept was triggered by something other than a key.

What do you think? Should I be using a different method to communicate the key information to the Validator? Would you take a change to add a "ValidationContext::key_event() -> Option<>" accessor if I submitted a PR, or is there a reason you don't agree with this direction?

Thank you.

Side Note: In a perfect world, both last_event and cursor_pos would be available to ValidationContext, but I can exfiltrate the cursor position through the Highlighter.

gwenn commented 11 months ago

Similar projects don't seem to expose those details either: https://docs.rs/reedline/latest/reedline/trait.Validator.html https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html?highlight=valid#input-validation https://python-prompt-toolkit.readthedocs.io/en/master/pages/reference.html#prompt_toolkit.validation.Validator

luketpeterson commented 11 months ago

Similar projects don't seem to expose those details either:

That's a good point. Exposing editor details in the Validator isn't very conceptually pure if the role of a Validator is just to validate a line.

My problem is that Validator does double duty first determining if a given Enter event should be a newline or not, and then whether the line should be accepted / rejected.

An equally good solution, that is conceptually cleaner would be a way to register a custom handler for the Enter KeyEvent, which would then decide whether to forward on a Cmd::Newline or a Cmd::AcceptOrInsertLine / Cmd::AcceptLine. Is this possible somehow?

gwenn commented 11 months ago

An equally good solution, that is conceptually cleaner would be a way to register a custom handler for the Enter KeyEvent, which would then decide whether to forward on a Cmd::Newline or a Cmd::AcceptOrInsertLine / Cmd::AcceptLine. Is this possible somehow?

You mean like https://docs.rs/rustyline/latest/rustyline/trait.ConditionalEventHandler.html ?

luketpeterson commented 11 months ago

You mean like https://docs.rs/rustyline/latest/rustyline/trait.ConditionalEventHandler.html ?

Exactly like that! I don't know how I missed that. 🤦 Thank you for the reply.

gwenn commented 11 months ago

I don't know how I missed that.

Mainly because rustyline documentation is not great like the one for python-prompt-toolkit.