mirror of
https://github.com/TECHNOFAB11/tmux-copyrat.git
synced 2025-12-12 16:10:07 +01:00
refactor: refactor
This commit is contained in:
parent
50391320ee
commit
58ceb190b6
4 changed files with 45 additions and 76 deletions
|
|
@ -429,13 +429,14 @@ fn main() -> Result<(), error::ParseError> {
|
||||||
// Screen, preventing copyrat::run to execute.
|
// Screen, preventing copyrat::run to execute.
|
||||||
let initial_pane = active_pane;
|
let initial_pane = active_pane;
|
||||||
|
|
||||||
// Create a new window without switching to it.
|
// Create a new window without switching to it, with a `sh` command
|
||||||
let temp_pane: tmux::Pane = tmux::create_new_window("[copyrat]")?;
|
// for faster startup.
|
||||||
|
let temp_pane: tmux::Pane = tmux::create_new_window("[copyrat]", "sh")?;
|
||||||
|
|
||||||
// Swap the two panes, changing the active pane to be the temp_pane.
|
// Swap the two panes, changing the active pane to be the temp_pane.
|
||||||
// After swap, temp_pane has the same height than the initial_pane
|
// After swap, temp_pane has the same height than the initial_pane
|
||||||
// had before being swapped.
|
// had before being swapped.
|
||||||
tmux::swap_panes(&initial_pane, &temp_pane)?;
|
tmux::swap_panes(initial_pane, &temp_pane)?;
|
||||||
|
|
||||||
// Running copyrat now will render in the newly created temp_pane
|
// Running copyrat now will render in the newly created temp_pane
|
||||||
// (locking stdin, writing to its stdout), but this is almost
|
// (locking stdin, writing to its stdout), but this is almost
|
||||||
|
|
@ -443,7 +444,7 @@ fn main() -> Result<(), error::ParseError> {
|
||||||
let selections = copyrat::run(buffer, &opt.cli_options);
|
let selections = copyrat::run(buffer, &opt.cli_options);
|
||||||
|
|
||||||
// Swap back the two panes, making initial_pane the active one again.
|
// Swap back the two panes, making initial_pane the active one again.
|
||||||
tmux::swap_panes(&temp_pane, &initial_pane)?;
|
tmux::swap_panes(&temp_pane, initial_pane)?;
|
||||||
|
|
||||||
tmux::kill_pane(&temp_pane)?;
|
tmux::kill_pane(&temp_pane)?;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -66,9 +66,7 @@ pub struct CliOpt {
|
||||||
// /// Which existing regexes to use.
|
// /// Which existing regexes to use.
|
||||||
// #[clap(short = "x", long, arg_enum)]
|
// #[clap(short = "x", long, arg_enum)]
|
||||||
// regex_id: Vec<regexes::RegexId>,
|
// regex_id: Vec<regexes::RegexId>,
|
||||||
|
//
|
||||||
// TODO: choose if pre-baked regexes is a good idea
|
|
||||||
// TODO: check if compiled regexes are possible
|
|
||||||
/// Additional regex patterns.
|
/// Additional regex patterns.
|
||||||
#[clap(short = "X", long)]
|
#[clap(short = "X", long)]
|
||||||
custom_regex: Vec<String>,
|
custom_regex: Vec<String>,
|
||||||
|
|
|
||||||
55
src/tmux.rs
55
src/tmux.rs
|
|
@ -124,47 +124,6 @@ pub fn get_options(prefix: &str) -> Result<HashMap<String, String>, ParseError>
|
||||||
Ok(args)
|
Ok(args)
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn toto() {
|
|
||||||
// let options_command = vec!["tmux", "show", "-g"];
|
|
||||||
// let params: Vec<String> = options_command.iter().map(|arg| arg.to_string()).collect();
|
|
||||||
// let options = self.executor.execute(params);
|
|
||||||
// let lines: Vec<&str> = options.split('\n').collect();
|
|
||||||
|
|
||||||
// let pattern = Regex::new(r#"@thumbs-([\w\-0-9]+) "?(\w+)"?"#).unwrap();
|
|
||||||
|
|
||||||
// let args = lines
|
|
||||||
// .iter()
|
|
||||||
// .flat_map(|line| {
|
|
||||||
// if let Some(captures) = pattern.captures(line) {
|
|
||||||
// let name = captures.get(1).unwrap().as_str();
|
|
||||||
// let value = captures.get(2).unwrap().as_str();
|
|
||||||
|
|
||||||
// let boolean_params = vec!["reverse", "unique", "contrast"];
|
|
||||||
|
|
||||||
// if boolean_params.iter().any(|&x| x == name) {
|
|
||||||
// return vec![format!("--{}", name)];
|
|
||||||
// }
|
|
||||||
|
|
||||||
// let string_params = vec![
|
|
||||||
// "position",
|
|
||||||
// "fg-color",
|
|
||||||
// "bg-color",
|
|
||||||
// "hint-bg-color",
|
|
||||||
// "hint-fg-color",
|
|
||||||
// "select-fg-color",
|
|
||||||
// "select-bg-color",
|
|
||||||
// ];
|
|
||||||
|
|
||||||
// if string_params.iter().any(|&x| x == name) {
|
|
||||||
// return vec![format!("--{}", name), format!("'{}'", value)];
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if name.starts_with("regexp") {
|
|
||||||
// return vec!["--regexp".to_string(), format!("'{}'", value)];
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// };}
|
|
||||||
|
|
||||||
#[derive(Clap, Debug)]
|
#[derive(Clap, Debug)]
|
||||||
pub enum CaptureRegion {
|
pub enum CaptureRegion {
|
||||||
/// The entire history.
|
/// The entire history.
|
||||||
|
|
@ -198,6 +157,10 @@ impl FromStr for CaptureRegion {
|
||||||
/// `CaptureRegion` specifies if the visible area is captured, or the entire
|
/// `CaptureRegion` specifies if the visible area is captured, or the entire
|
||||||
/// history.
|
/// history.
|
||||||
///
|
///
|
||||||
|
/// # TODO
|
||||||
|
///
|
||||||
|
/// Capture with `capture-pane -J` joins wrapped lines.
|
||||||
|
///
|
||||||
/// # Note
|
/// # Note
|
||||||
///
|
///
|
||||||
/// If the pane is in normal mode, capturing the visible area can be done
|
/// If the pane is in normal mode, capturing the visible area can be done
|
||||||
|
|
@ -234,16 +197,18 @@ pub fn capture_pane(pane: &Pane, region: &CaptureRegion) -> Result<String, Parse
|
||||||
// scroll_params,
|
// scroll_params,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a new named window in the background (without switching to it) and
|
/// Creates a new named window in the background (without switching to it)
|
||||||
/// returns a `Pane` describing the newly created pane.
|
/// executing the provided command (probably `sh`) and returns a `Pane`
|
||||||
|
/// describing the newly created pane.
|
||||||
///
|
///
|
||||||
/// # Note
|
/// # Note
|
||||||
///
|
///
|
||||||
/// Returning a new `Pane` seems overkill, given we mostly take care of its
|
/// Returning a new `Pane` seems overkill, given we mostly take care of its
|
||||||
/// Id, but it is cleaner.
|
/// Id, but it is cleaner.
|
||||||
pub fn create_new_window(name: &str) -> Result<Pane, ParseError> {
|
pub fn create_new_window(name: &str, command: &str) -> Result<Pane, ParseError> {
|
||||||
let args = vec!["new-window", "-P", "-d", "-n", name, "-F",
|
let args = vec!["new-window", "-P", "-d", "-n", name, "-F",
|
||||||
"#{pane_id}:#{?pane_in_mode,true,false}:#{pane_height}:#{scroll_position}:#{?pane_active,true,false}"];
|
"#{pane_id}:#{?pane_in_mode,true,false}:#{pane_height}:#{scroll_position}:#{?pane_active,true,false}",
|
||||||
|
command];
|
||||||
|
|
||||||
let output = process::execute("tmux", &args)?;
|
let output = process::execute("tmux", &args)?;
|
||||||
|
|
||||||
|
|
|
||||||
53
src/view.rs
53
src/view.rs
|
|
@ -3,14 +3,9 @@ use super::{colors, state};
|
||||||
use crate::error::ParseError;
|
use crate::error::ParseError;
|
||||||
use clap::Clap;
|
use clap::Clap;
|
||||||
use std::char;
|
use std::char;
|
||||||
use std::io::{stdout, Read, Write};
|
use std::io;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use termion::async_stdin;
|
use termion::{self, color, cursor, event, style};
|
||||||
use termion::event::Key;
|
|
||||||
use termion::input::TermRead;
|
|
||||||
use termion::raw::IntoRawMode;
|
|
||||||
use termion::screen::AlternateScreen;
|
|
||||||
use termion::{color, cursor, style};
|
|
||||||
|
|
||||||
pub struct View<'a> {
|
pub struct View<'a> {
|
||||||
state: &'a mut state::State<'a>,
|
state: &'a mut state::State<'a>,
|
||||||
|
|
@ -149,7 +144,7 @@ impl<'a> View<'a> {
|
||||||
/// # Notes
|
/// # Notes
|
||||||
/// - All trailing whitespaces are trimmed, empty lines are skipped.
|
/// - All trailing whitespaces are trimmed, empty lines are skipped.
|
||||||
/// - This writes directly on the writer, avoiding extra allocation.
|
/// - This writes directly on the writer, avoiding extra allocation.
|
||||||
fn render_lines(stdout: &mut dyn Write, lines: &Vec<&str>) -> () {
|
fn render_lines(stdout: &mut dyn io::Write, lines: &Vec<&str>) -> () {
|
||||||
for (index, line) in lines.iter().enumerate() {
|
for (index, line) in lines.iter().enumerate() {
|
||||||
let trimmed_line = line.trim_end();
|
let trimmed_line = line.trim_end();
|
||||||
|
|
||||||
|
|
@ -172,7 +167,7 @@ impl<'a> View<'a> {
|
||||||
/// # Note
|
/// # Note
|
||||||
/// This writes directly on the writer, avoiding extra allocation.
|
/// This writes directly on the writer, avoiding extra allocation.
|
||||||
fn render_matched_text(
|
fn render_matched_text(
|
||||||
stdout: &mut dyn Write,
|
stdout: &mut dyn io::Write,
|
||||||
text: &str,
|
text: &str,
|
||||||
focused: bool,
|
focused: bool,
|
||||||
offset: (usize, usize),
|
offset: (usize, usize),
|
||||||
|
|
@ -210,7 +205,7 @@ impl<'a> View<'a> {
|
||||||
/// # Note
|
/// # Note
|
||||||
/// This writes directly on the writer, avoiding extra allocation.
|
/// This writes directly on the writer, avoiding extra allocation.
|
||||||
fn render_matched_hint(
|
fn render_matched_hint(
|
||||||
stdout: &mut dyn Write,
|
stdout: &mut dyn io::Write,
|
||||||
hint_text: &str,
|
hint_text: &str,
|
||||||
offset: (usize, usize),
|
offset: (usize, usize),
|
||||||
colors: &ViewColors,
|
colors: &ViewColors,
|
||||||
|
|
@ -299,7 +294,7 @@ impl<'a> View<'a> {
|
||||||
/// # Note
|
/// # Note
|
||||||
/// Multibyte characters are taken into account, so that the Match's `text`
|
/// Multibyte characters are taken into account, so that the Match's `text`
|
||||||
/// and `hint` are rendered in their proper position.
|
/// and `hint` are rendered in their proper position.
|
||||||
fn render(&self, stdout: &mut dyn Write) -> () {
|
fn render(&self, stdout: &mut dyn io::Write) -> () {
|
||||||
write!(stdout, "{}", cursor::Hide).unwrap();
|
write!(stdout, "{}", cursor::Hide).unwrap();
|
||||||
|
|
||||||
// 1. Trim all lines and render non-empty ones.
|
// 1. Trim all lines and render non-empty ones.
|
||||||
|
|
@ -359,7 +354,9 @@ impl<'a> View<'a> {
|
||||||
/// # Panics
|
/// # Panics
|
||||||
/// This function panics if termion cannot read the entered keys on stdin.
|
/// This function panics if termion cannot read the entered keys on stdin.
|
||||||
/// This function also panics if the user types Insert on a line without hints.
|
/// This function also panics if the user types Insert on a line without hints.
|
||||||
fn listen(&mut self, stdin: &mut dyn Read, stdout: &mut dyn Write) -> CaptureEvent {
|
fn listen(&mut self, reader: &mut dyn io::Read, writer: &mut dyn io::Write) -> CaptureEvent {
|
||||||
|
use termion::input::TermRead; // Trait for `reader.keys().next()`.
|
||||||
|
|
||||||
if self.matches.is_empty() {
|
if self.matches.is_empty() {
|
||||||
return CaptureEvent::Exit;
|
return CaptureEvent::Exit;
|
||||||
}
|
}
|
||||||
|
|
@ -374,11 +371,11 @@ impl<'a> View<'a> {
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.clone();
|
.clone();
|
||||||
|
|
||||||
self.render(stdout);
|
self.render(writer);
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
// This is an option of a result of a key... Let's pop error cases first.
|
// This is an option of a result of a key... Let's pop error cases first.
|
||||||
let next_key = stdin.keys().next();
|
let next_key = reader.keys().next();
|
||||||
|
|
||||||
if next_key.is_none() {
|
if next_key.is_none() {
|
||||||
// Nothing in the buffer. Wait for a bit...
|
// Nothing in the buffer. Wait for a bit...
|
||||||
|
|
@ -394,7 +391,7 @@ impl<'a> View<'a> {
|
||||||
|
|
||||||
match key_res.unwrap() {
|
match key_res.unwrap() {
|
||||||
// Clears an ongoing multi-hint selection, or exit.
|
// Clears an ongoing multi-hint selection, or exit.
|
||||||
Key::Esc => {
|
event::Key::Esc => {
|
||||||
if self.multi && !typed_hint.is_empty() {
|
if self.multi && !typed_hint.is_empty() {
|
||||||
typed_hint.clear();
|
typed_hint.clear();
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -405,7 +402,7 @@ impl<'a> View<'a> {
|
||||||
// In multi-selection mode, this appends the selected hint to the
|
// In multi-selection mode, this appends the selected hint to the
|
||||||
// vector of selections. In normal mode, this returns with the hint
|
// vector of selections. In normal mode, this returns with the hint
|
||||||
// selected.
|
// selected.
|
||||||
Key::Insert => match self.matches.get(self.focus_index) {
|
event::Key::Insert => match self.matches.get(self.focus_index) {
|
||||||
Some(mat) => {
|
Some(mat) => {
|
||||||
chosen.push((mat.text.to_string(), false));
|
chosen.push((mat.text.to_string(), false));
|
||||||
|
|
||||||
|
|
@ -417,15 +414,15 @@ impl<'a> View<'a> {
|
||||||
},
|
},
|
||||||
|
|
||||||
// Move focus to next/prev match.
|
// Move focus to next/prev match.
|
||||||
Key::Up => self.prev(),
|
event::Key::Up => self.prev(),
|
||||||
Key::Down => self.next(),
|
event::Key::Down => self.next(),
|
||||||
Key::Left => self.prev(),
|
event::Key::Left => self.prev(),
|
||||||
Key::Right => self.next(),
|
event::Key::Right => self.next(),
|
||||||
|
|
||||||
// Pressing space finalizes an ongoing multi-hint selection (without
|
// Pressing space finalizes an ongoing multi-hint selection (without
|
||||||
// selecting the focused match). Pressing other characters attempts at
|
// selecting the focused match). Pressing other characters attempts at
|
||||||
// finding a match with a corresponding hint.
|
// finding a match with a corresponding hint.
|
||||||
Key::Char(ch) => {
|
event::Key::Char(ch) => {
|
||||||
if ch == ' ' && self.multi {
|
if ch == ' ' && self.multi {
|
||||||
return CaptureEvent::Hint(chosen);
|
return CaptureEvent::Hint(chosen);
|
||||||
}
|
}
|
||||||
|
|
@ -468,15 +465,23 @@ impl<'a> View<'a> {
|
||||||
|
|
||||||
// Render on stdout if we did not exit earlier (move focus,
|
// Render on stdout if we did not exit earlier (move focus,
|
||||||
// multi-selection).
|
// multi-selection).
|
||||||
self.render(stdout);
|
self.render(writer);
|
||||||
}
|
}
|
||||||
|
|
||||||
CaptureEvent::Exit
|
CaptureEvent::Exit
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn present(&mut self) -> Vec<(String, bool)> {
|
pub fn present(&mut self) -> Vec<(String, bool)> {
|
||||||
let mut stdin = async_stdin();
|
use std::io::Write;
|
||||||
let mut stdout = AlternateScreen::from(stdout().into_raw_mode().unwrap());
|
use termion::raw::IntoRawMode;
|
||||||
|
use termion::screen::AlternateScreen;
|
||||||
|
|
||||||
|
let mut stdin = termion::async_stdin();
|
||||||
|
let mut stdout = AlternateScreen::from(
|
||||||
|
io::stdout()
|
||||||
|
.into_raw_mode()
|
||||||
|
.expect("Cannot access alternate screen."),
|
||||||
|
);
|
||||||
|
|
||||||
let hints = match self.listen(&mut stdin, &mut stdout) {
|
let hints = match self.listen(&mut stdin, &mut stdout) {
|
||||||
CaptureEvent::Exit => vec![],
|
CaptureEvent::Exit => vec![],
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue