Edit editor contents externally

This commit is contained in:
Joscha 2022-08-02 00:42:52 +02:00
parent 415da3afd8
commit fe0f6c7520
2 changed files with 27 additions and 3 deletions

View file

@ -3,11 +3,15 @@ use std::sync::Arc;
use parking_lot::FairMutex; use parking_lot::FairMutex;
use toss::terminal::Terminal; use toss::terminal::Terminal;
pub fn prompt(terminal: &mut Terminal, crossterm_lock: &Arc<FairMutex<()>>) -> Option<String> { pub fn prompt(
terminal: &mut Terminal,
crossterm_lock: &Arc<FairMutex<()>>,
initial_text: &str,
) -> Option<String> {
let content = { let content = {
let _guard = crossterm_lock.lock(); let _guard = crossterm_lock.lock();
terminal.suspend().expect("could not suspend"); terminal.suspend().expect("could not suspend");
let content = edit::edit(""); let content = edit::edit(initial_text);
terminal.unsuspend().expect("could not unsuspend"); terminal.unsuspend().expect("could not unsuspend");
content content
}; };

View file

@ -2,11 +2,14 @@ use std::iter;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use parking_lot::Mutex; use parking_lot::{FairMutex, Mutex};
use toss::frame::{Frame, Pos, Size}; use toss::frame::{Frame, Pos, Size};
use toss::styled::Styled; use toss::styled::Styled;
use toss::terminal::Terminal;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use crate::ui::util;
use super::Widget; use super::Widget;
/////////// ///////////
@ -66,6 +69,12 @@ impl InnerEditorState {
panic!("cursor index out of bounds"); panic!("cursor index out of bounds");
} }
fn set_text(&mut self, text: String) {
self.text = text;
self.idx = self.idx.min(self.text.len());
self.move_cursor_to_grapheme_boundary();
}
/// Insert a character at the current cursor position and move the cursor /// Insert a character at the current cursor position and move the cursor
/// accordingly. /// accordingly.
fn insert_char(&mut self, ch: char) { fn insert_char(&mut self, ch: char) {
@ -201,6 +210,10 @@ impl EditorState {
self.0.lock().text.clone() self.0.lock().text.clone()
} }
pub fn set_text(&self, text: String) {
self.0.lock().set_text(text);
}
pub fn insert_char(&self, ch: char) { pub fn insert_char(&self, ch: char) {
self.0.lock().insert_char(ch); self.0.lock().insert_char(ch);
} }
@ -222,6 +235,13 @@ impl EditorState {
pub fn move_cursor_right(&self) { pub fn move_cursor_right(&self) {
self.0.lock().move_cursor_right(); self.0.lock().move_cursor_right();
} }
pub fn edit_externally(&self, terminal: &mut Terminal, crossterm_lock: &Arc<FairMutex<()>>) {
let mut guard = self.0.lock();
if let Some(text) = util::prompt(terminal, crossterm_lock, &guard.text) {
guard.set_text(text);
}
}
} }
//////////// ////////////