Skip to content

Commit

Permalink
Subscribe the events per plugin instead of publishing them to all (#1016
Browse files Browse the repository at this point in the history
)

* Rename PluginAction to ActionRequest

* Make PluginAction strongly typed

* Rename syntax_highlighter.rs to syntax.rs

* Refine cursorword plugin

* Remove colorsys dep

* Change to subscriptions

* nits

* Introduce `#[maple_derive::subscriptions]`

* Add tests for maple_derive

* clippy fixes

* docs

* Nits
  • Loading branch information
liuchengxu authored Nov 8, 2023
1 parent c8e024a commit 54fe3bb
Show file tree
Hide file tree
Showing 28 changed files with 891 additions and 417 deletions.
16 changes: 9 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions autoload/clap/api.vim
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,13 @@ function! s:api.echomsg(msg) abort
echomsg a:msg
endfunction

function! s:api.verbose(cmd) abort
redir => l:output
silent execute ':verbose' a:cmd
redir END
return l:output
endfunction

function! s:api.set_initial_query(query) abort
if a:query ==# '@visual'
let query = clap#util#get_visual_selection()
Expand Down
14 changes: 14 additions & 0 deletions autoload/clap/plugin/cursorword.vim
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ hi ClapUnderline gui=underline cterm=underline
hi default link ClapCursorWord IncSearch
hi default link ClapCursorWordTwins ClapUnderline

augroup VimClapCursorword
autocmd!

autocmd ColorScheme * call clap#client#notify('cursorword/__define-highlights', [+expand('<abuf>')])
augroup END

function! clap#plugin#cursorword#add_highlights(word_highlights) abort
let cword_len = a:word_highlights.cword_len
let match_ids = []
Expand All @@ -26,5 +32,13 @@ function! clap#plugin#cursorword#add_highlights(word_highlights) abort
return match_ids
endfunction

function! clap#plugin#cursorword#define_highlights(highlights, twins_highlights) abort
let [ctermbg, guibg] = a:highlights
let [twins_ctermbg, twins_guibg] = a:twins_highlights

execute printf('highlight ClapCursorWord ctermbg=%d guibg=%s', ctermbg, guibg)
execute printf('highlight ClapCursorWordTwins ctermbg=%d guibg=%s', twins_ctermbg, twins_guibg)
endfunction

let &cpoptions = s:save_cpo
unlet s:save_cpo
1 change: 0 additions & 1 deletion crates/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ cargo_metadata = "0.18.0"
chrono = { version = "0.4", features = ["serde"] }
chrono-humanize = "0.2.3"
clap = { version = "4.2", features = ["derive"] }
colorsys = "0.6.7"
colors-transform = "0.2.11"
directories = "4.0"
futures = "0.3"
Expand Down
2 changes: 1 addition & 1 deletion crates/highlighter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"

[dependencies]
anyhow = { workspace = true }
colorsys = { workspace = true }
colors-transform = { workspace = true }
once_cell = { workspace = true }
rgb2ansi256 = { workspace = true }
serde = { workspace = true, features = ["derive"] }
Expand Down
26 changes: 13 additions & 13 deletions crates/highlighter/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Result;
use colorsys::Rgb;
use colors_transform::{AlphaColor, Color as ColorT, Rgb};
use rgb2ansi256::rgb_to_ansi256;
use std::ops::Range;
use syntect::highlighting::{
Expand Down Expand Up @@ -44,22 +44,22 @@ impl HighlightArgs {
FontStyle::ITALIC => AttrList::Italic,
_ => AttrList::None,
};
let guifg = Rgb::from(&(
let guifg = Rgb::from_tuple(&(
style.foreground.r as f32,
style.foreground.g as f32,
style.foreground.b as f32,
style.foreground.a as f32,
));
))
.set_alpha(style.foreground.a as f32);

let ctermfg = rgb_to_ansi256(style.foreground.r, style.foreground.g, style.foreground.b);

let gui = cterm.clone();
let guibg = Rgb::from(&(
let guibg = Rgb::from_tuple(&(
style.background.r as f32,
style.background.g as f32,
style.background.b as f32,
style.background.a as f32,
));
))
.set_alpha(style.background.a as f32);
let ctermbg = rgb_to_ansi256(style.background.r, style.background.g, style.background.b);

Self {
Expand Down Expand Up @@ -137,8 +137,8 @@ impl<'a> HighlightEngine<'a> {
let char_indices = Vec::from_iter(offset - chars_count..offset);
let byte_indices = utils::char_indices_to_byte_indices(line, &char_indices);
let highlight_args = HighlightArgs::from_style(style);
let hex_guifg = highlight_args.guifg.to_hex_string();
let hex_guibg = highlight_args.guibg.to_hex_string();
let hex_guifg = highlight_args.guifg.to_css_hex_string();
let hex_guibg = highlight_args.guibg.to_css_hex_string();
let group_name: String =
format!("ClapHighlighter_{}_{}", &hex_guifg[1..], &hex_guifg[1..]);
Some(TokenHighlight {
Expand Down Expand Up @@ -204,16 +204,16 @@ impl SyntaxHighlighter {
.get(theme)
.and_then(|theme| theme.settings.foreground)
{
let guifg = Rgb::from(&(
let guifg = Rgb::from_tuple(&(
normal_fg_color.r as f32,
normal_fg_color.g as f32,
normal_fg_color.b as f32,
normal_fg_color.a as f32,
));
))
.set_alpha(normal_fg_color.a as f32);

let ctermfg = rgb_to_ansi256(normal_fg_color.r, normal_fg_color.g, normal_fg_color.b);

Some((guifg.to_hex_string(), ctermfg))
Some((guifg.to_css_hex_string(), ctermfg))
} else {
None
}
Expand Down
2 changes: 1 addition & 1 deletion crates/maple_core/src/stdio_server/handler/on_move.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::previewer;
use crate::previewer::vim_help::HelpTagPreview;
use crate::previewer::{get_file_preview, FilePreview};
use crate::stdio_server::job;
use crate::stdio_server::plugin::syntax_highlighter::{highlight_lines, HIGHLIGHTER};
use crate::stdio_server::plugin::syntax::{highlight_lines, HIGHLIGHTER};
use crate::stdio_server::provider::{read_dir_entries, Context, ProviderSource};
use crate::stdio_server::vim::preview_syntax;
use crate::tools::ctags::{current_context_tag_async, BufferTag};
Expand Down
25 changes: 6 additions & 19 deletions crates/maple_core/src/stdio_server/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ use rpc::{Params, RpcNotification};
use std::collections::{HashMap, HashSet, VecDeque};
use tokio::sync::mpsc::UnboundedSender;

pub use types::AutocmdEventType;

pub type KeyEvent = (KeyEventType, Params);
pub type AutocmdEvent = (AutocmdEventType, Params);

#[derive(Debug, Clone)]
pub enum PluginEvent {
Autocmd(AutocmdEvent),
Action(PluginAction),
Action(ActionRequest),
}

impl PluginEvent {
Expand Down Expand Up @@ -68,30 +70,15 @@ pub enum KeyEventType {
CtrlP,
}

/// Represents a key event.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
pub enum AutocmdEventType {
CursorMoved,
InsertEnter,
BufEnter,
BufLeave,
BufDelete,
BufWritePost,
BufWinEnter,
BufWinLeave,
TextChanged,
TextChangedI,
}

pub type ActionEvent = (PluginId, PluginAction);
pub type ActionEvent = (PluginId, ActionRequest);

#[derive(Debug, Clone)]
pub struct PluginAction {
pub struct ActionRequest {
pub method: String,
pub params: Params,
}

impl From<RpcNotification> for PluginAction {
impl From<RpcNotification> for ActionRequest {
fn from(notification: RpcNotification) -> Self {
Self {
method: notification.method,
Expand Down
4 changes: 2 additions & 2 deletions crates/maple_core/src/stdio_server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ struct InitializedService {
/// Create a new service, with plugins registered from the config file.
fn initialize_service(vim: Vim) -> InitializedService {
use self::plugin::{
ActionType, ClapPlugin, ColorizerPlugin, CtagsPlugin, CursorWordPlugin, GitPlugin,
ActionType, ClapPlugin, ColorizerPlugin, CtagsPlugin, CursorwordPlugin, GitPlugin,
LinterPlugin, MarkdownPlugin, SyntaxHighlighterPlugin, SystemPlugin,
};

Expand Down Expand Up @@ -122,7 +122,7 @@ fn initialize_service(vim: Vim) -> InitializedService {
}

if plugin_config.cursorword.enable {
register_plugin(Box::new(CursorWordPlugin::new(vim)), None);
register_plugin(Box::new(CursorwordPlugin::new(vim)), None);
}

InitializedService {
Expand Down
17 changes: 5 additions & 12 deletions crates/maple_core/src/stdio_server/plugin/colorizer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::stdio_server::input::{AutocmdEvent, PluginAction};
use crate::stdio_server::input::ActionRequest;
use crate::stdio_server::plugin::{ClapPlugin, Toggle};
use crate::stdio_server::vim::Vim;
use anyhow::Result;
Expand Down Expand Up @@ -195,11 +195,9 @@ fn parse<T: std::str::FromStr>(caps: &regex::Captures, i: usize) -> Option<T> {

#[async_trait::async_trait]
impl ClapPlugin for ColorizerPlugin {
async fn handle_action(&mut self, action: PluginAction) -> Result<()> {
let PluginAction { method, params: _ } = action;

match method.as_str() {
Self::TOGGLE => {
async fn handle_action(&mut self, action: ActionRequest) -> Result<()> {
match self.parse_action(&action.method)? {
ColorizerAction::Toggle => {
let bufnr = self.vim.bufnr("").await?;

if self.toggle.is_off() {
Expand All @@ -216,20 +214,15 @@ impl ClapPlugin for ColorizerPlugin {

self.toggle.switch();
}
Self::OFF => {
ColorizerAction::Off => {
let bufnr = self.vim.bufnr("").await?;
self.vim
.exec("clap#plugin#colorizer#clear_highlights", bufnr)?;
}
_ => {}
}

Ok(())
}

async fn handle_autocmd(&mut self, _autocmd: AutocmdEvent) -> Result<()> {
Ok(())
}
}

#[cfg(test)]
Expand Down
11 changes: 8 additions & 3 deletions crates/maple_core/src/stdio_server/plugin/ctags.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::stdio_server::input::{AutocmdEvent, AutocmdEventType, PluginAction};
use crate::stdio_server::input::{ActionRequest, AutocmdEvent, AutocmdEventType};
use crate::stdio_server::plugin::ClapPlugin;
use crate::stdio_server::vim::Vim;
use crate::tools::ctags::{BufferTag, Scope};
Expand Down Expand Up @@ -93,10 +93,11 @@ impl CtagsPlugin {

#[async_trait::async_trait]
impl ClapPlugin for CtagsPlugin {
async fn handle_action(&mut self, _action: PluginAction) -> Result<()> {
async fn handle_action(&mut self, _action: ActionRequest) -> Result<()> {
Ok(())
}

#[maple_derive::subscriptions]
async fn handle_autocmd(&mut self, autocmd: AutocmdEvent) -> Result<()> {
use AutocmdEventType::{BufDelete, BufEnter, BufWritePost, CursorMoved};

Expand All @@ -118,7 +119,11 @@ impl ClapPlugin for CtagsPlugin {
self.buf_tags.remove(&bufnr);
}
CursorMoved => self.on_cursor_moved(bufnr).await?,
_ => {}
event => {
return Err(anyhow::anyhow!(
"Unhandled {event:?}, incomplete subscriptions?",
))
}
}

Ok(())
Expand Down
Loading

0 comments on commit 54fe3bb

Please sign in to comment.