curd-editor 0.10.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
use std::io::{stdout, Write};

#[cfg(test)]
mod tests;

use crossterm::{
    event::{
        DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
        EnableFocusChange, EnableMouseCapture,
    },
    execute,
    terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
};

pub struct Terminal;

impl Terminal {
    pub fn start() -> std::io::Result<Self> {
        terminal::enable_raw_mode()?;
        // Bracketed paste makes the terminal hand over pasted text in one
        // piece, so it can be inserted as-is instead of as typed keys.
        // Mouse capture reports clicks and the wheel; focus reports say when
        // the user comes back from another window.
        execute!(
            stdout(),
            EnterAlternateScreen,
            EnableBracketedPaste,
            EnableMouseCapture,
            EnableFocusChange
        )?;
        Ok(Self)
    }

    pub fn size() -> std::io::Result<(usize, usize)> {
        let (width, height) = terminal::size()?;
        Ok((width as usize, height as usize))
    }
}

/// More than this is not sent to the system clipboard: terminals refuse
/// long sequences. It can still be pasted inside the editor.
const MAX_CLIPBOARD_BYTES: usize = 100_000;

/// `bytes` in base64, which is how the terminal wants clipboard text.
fn base64(bytes: &[u8]) -> String {
    const LETTERS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::new();
    for chunk in bytes.chunks(3) {
        let group = chunk.iter().fold(0u32, |group, byte| group << 8 | *byte as u32) << (8 * (3 - chunk.len()));
        for position in 0..4 {
            if position <= chunk.len() {
                out.push(LETTERS[(group >> (18 - 6 * position) & 63) as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

/// What to write to the terminal to put `text` on the system clipboard
/// (the "OSC 52" sequence). Terminals that do not know it ignore it.
fn clipboard_sequence(text: &str) -> Option<String> {
    (text.len() <= MAX_CLIPBOARD_BYTES).then(|| format!("\x1b]52;c;{}\x07", base64(text.as_bytes())))
}

impl Terminal {
    /// Puts `text` on the system clipboard, where the terminal allows it.
    pub fn copy(text: &str) -> std::io::Result<()> {
        if let Some(sequence) = clipboard_sequence(text) {
            let mut out = stdout();
            out.write_all(sequence.as_bytes())?;
            out.flush()?;
        }
        Ok(())
    }
}

impl Drop for Terminal {
    fn drop(&mut self) {
        let _ = execute!(
            stdout(),
            DisableFocusChange,
            DisableMouseCapture,
            DisableBracketedPaste,
            LeaveAlternateScreen
        );
        let _ = terminal::disable_raw_mode();
    }
}