repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/time.rs | yazi-plugin/src/utils/time.rs | use std::time::{SystemTime, UNIX_EPOCH};
use mlua::{ExternalError, Function, Lua};
use super::Utils;
impl Utils {
pub(super) fn time(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, ()| {
Ok(SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).ok())
})
}
pub(super) fn sleep(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|_, secs: f64| async move {
if secs < 0.0 {
return Err("negative sleep duration".into_lua_err());
}
tokio::time::sleep(tokio::time::Duration::from_secs_f64(secs)).await;
Ok(())
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/log.rs | yazi-plugin/src/utils/log.rs | use mlua::{Function, Lua, MultiValue};
use tracing::{debug, error};
use super::Utils;
impl Utils {
pub(super) fn dbg(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, values: MultiValue| {
let s = values.into_iter().map(|v| format!("{v:#?}")).collect::<Vec<_>>().join(" ");
Ok(debug!("{s}"))
})
}
pub(super) fn err(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, values: MultiValue| {
let s = values.into_iter().map(|v| format!("{v:#?}")).collect::<Vec<_>>().join(" ");
Ok(error!("{s}"))
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/json.rs | yazi-plugin/src/utils/json.rs | use mlua::{Function, IntoLuaMulti, Lua, LuaSerdeExt, Value};
use yazi_binding::{Error, SER_OPT};
use super::Utils;
impl Utils {
pub(super) fn json_encode(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, value: Value| async move {
match serde_json::to_string(&value) {
Ok(s) => s.into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Serde(e)).into_lua_multi(&lua),
}
})
}
pub(super) fn json_decode(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, s: mlua::String| async move {
match serde_json::from_slice::<serde_json::Value>(&s.as_bytes()) {
Ok(v) => lua.to_value_with(&v, SER_OPT)?.into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Serde(e)).into_lua_multi(&lua),
}
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/target.rs | yazi-plugin/src/utils/target.rs | use mlua::{Function, Lua};
use super::Utils;
impl Utils {
pub(super) fn target_os(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, ()| Ok(std::env::consts::OS))
}
pub(super) fn target_family(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, ()| Ok(std::env::consts::FAMILY))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/layer.rs | yazi-plugin/src/utils/layer.rs | use std::{str::FromStr, time::Duration};
use mlua::{ExternalError, ExternalResult, Function, IntoLuaMulti, Lua, Table, Value};
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use yazi_binding::{deprecate, elements::{Line, Pos, Text}, runtime};
use yazi_config::{keymap::{Chord, Key}, popup::{ConfirmCfg, InputCfg}};
use yazi_macro::relay;
use yazi_parser::which::ShowOpt;
use yazi_proxy::{AppProxy, ConfirmProxy, InputProxy, WhichProxy};
use yazi_shared::Debounce;
use super::Utils;
use crate::bindings::InputRx;
impl Utils {
pub(super) fn which(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, t: Table| async move {
if runtime!(lua)?.initing {
return Err("Cannot call `ya.which()` during app initialization".into_lua_err());
}
let (tx, mut rx) = mpsc::channel::<usize>(1);
let cands: Vec<_> = t
.raw_get::<Table>("cands")?
.sequence_values::<Table>()
.enumerate()
.map(|(i, cand)| {
let cand = cand?;
Ok(Chord {
on: Self::parse_keys(cand.raw_get("on")?)?,
run: vec![relay!(which:callback, [i]).with_any("tx", tx.clone())],
desc: cand.raw_get("desc").ok(),
r#for: None,
})
})
.collect::<mlua::Result<_>>()?;
drop(tx);
WhichProxy::show(ShowOpt { cands, silent: t.raw_get("silent").unwrap_or_default() });
Ok(rx.recv().await.map(|idx| idx + 1))
})
}
pub(super) fn input(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, t: Table| async move {
if runtime!(lua)?.initing {
return Err("Cannot call `ya.input()` during app initialization".into_lua_err());
}
let mut pos = t.raw_get::<Value>("pos")?;
if pos.is_nil() {
pos = t.raw_get("position")?;
if !pos.is_nil() {
deprecate!(lua, "The `position` property of `ya.input()` is deprecated, use `pos` instead in your {}\nSee #2921 for more details: https://github.com/sxyazi/yazi/pull/2921");
}
}
let realtime = t.raw_get("realtime").unwrap_or_default();
let rx = UnboundedReceiverStream::new(InputProxy::show(InputCfg {
title: t.raw_get("title")?,
value: t.raw_get("value").unwrap_or_default(),
cursor: None, // TODO
obscure: t.raw_get("obscure").unwrap_or_default(),
position: Pos::new_input(pos)?.into(),
realtime,
completion: false,
}));
if !realtime {
return InputRx::consume(rx).await.into_lua_multi(&lua);
}
let debounce = t.raw_get::<f64>("debounce").unwrap_or_default();
if debounce < 0.0 {
Err("negative debounce duration".into_lua_err())
} else if debounce == 0.0 {
InputRx::new(rx).into_lua_multi(&lua)
} else {
InputRx::new(Debounce::new(rx, Duration::from_secs_f64(debounce))).into_lua_multi(&lua)
}
})
}
pub(super) fn confirm(lua: &Lua) -> mlua::Result<Function> {
fn body(t: &Table) -> mlua::Result<ratatui::widgets::Paragraph<'static>> {
Ok(match t.raw_get::<Value>("body")? {
Value::Nil => Default::default(),
v => Text::try_from(v)?.into(),
})
}
lua.create_async_function(|lua, t: Table| async move {
if runtime!(lua)?.initing {
return Err("Cannot call `ya.confirm()` during app initialization".into_lua_err());
}
let result = ConfirmProxy::show(ConfirmCfg {
position: Pos::try_from(t.raw_get::<Value>("pos")?)?.into(),
title: Line::try_from(t.raw_get::<Value>("title")?)?.into(),
body: body(&t)?,
list: Default::default(), // TODO
});
Ok(result.await)
})
}
pub(super) fn notify(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, t: Table| {
AppProxy::notify(t.try_into()?);
Ok(())
})
}
fn parse_keys(value: Value) -> mlua::Result<Vec<Key>> {
Ok(match value {
Value::String(s) => {
vec![Key::from_str(&s.to_str()?).into_lua_err()?]
}
Value::Table(t) => {
let mut v = Vec::with_capacity(10);
for s in t.sequence_values::<mlua::String>() {
v.push(Key::from_str(&s?.to_str()?).into_lua_err()?);
}
v
}
_ => Err("invalid `on`".into_lua_err())?,
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/text.rs | yazi-plugin/src/utils/text.rs | use mlua::{Function, Lua, Table};
use twox_hash::XxHash3_128;
use unicode_width::UnicodeWidthChar;
use yazi_binding::deprecate;
use yazi_widgets::CLIPBOARD;
use super::Utils;
impl Utils {
pub(super) fn hash(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(move |_, s: mlua::String| async move {
Ok(format!("{:x}", XxHash3_128::oneshot(&s.as_bytes())))
})
}
pub(super) fn quote(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, (s, unix): (mlua::String, Option<bool>)| {
let b = s.as_bytes();
let s = match unix {
Some(true) => yazi_shared::shell::unix::escape_os_bytes(&b),
Some(false) => yazi_shared::shell::windows::escape_os_bytes(&b),
None => yazi_shared::shell::escape_os_bytes(&b),
};
lua.create_string(&*s)
})
}
pub(super) fn truncate(lua: &Lua) -> mlua::Result<Function> {
fn traverse(
it: impl Iterator<Item = (usize, char)>,
max: usize,
) -> (Option<usize>, usize, bool) {
let (mut adv, mut last) = (0, 0);
let idx = it
.take_while(|&(_, c)| {
(last, adv) = (adv, adv + c.width().unwrap_or(0));
adv <= max
})
.map(|(i, _)| i)
.last();
(idx, last, adv > max)
}
lua.create_function(|lua, (s, t): (mlua::String, Table)| {
deprecate!(lua, "`ya.truncate()` is deprecated, use `ui.truncate()` instead, in your {}\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");
let b = s.as_bytes();
if b.is_empty() {
return Ok(s);
}
let max = t.raw_get("max")?;
if b.len() <= max {
return Ok(s);
} else if max < 1 {
return lua.create_string("");
}
let lossy = String::from_utf8_lossy(&b);
let rtl = t.raw_get("rtl").unwrap_or(false);
let (idx, width, remain) = if rtl {
traverse(lossy.char_indices().rev(), max)
} else {
traverse(lossy.char_indices(), max)
};
let Some(idx) = idx else { return lua.create_string("…") };
if !remain {
return Ok(s);
}
let result: Vec<_> = match (rtl, width == max) {
(false, false) => {
let len = lossy[idx..].chars().next().map_or(0, |c| c.len_utf8());
lossy[..idx + len].bytes().chain("…".bytes()).collect()
}
(false, true) => lossy[..idx].bytes().chain("…".bytes()).collect(),
(true, false) => "…".bytes().chain(lossy[idx..].bytes()).collect(),
(true, true) => {
let len = lossy[idx..].chars().next().map_or(0, |c| c.len_utf8());
"…".bytes().chain(lossy[idx + len..].bytes()).collect()
}
};
lua.create_string(result)
})
}
pub(super) fn clipboard(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, text: Option<String>| async move {
if let Some(text) = text {
CLIPBOARD.set(text).await;
Ok(None)
} else {
Some(lua.create_string(CLIPBOARD.get().await)).transpose()
}
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/utils.rs | yazi-plugin/src/utils/utils.rs | use mlua::{IntoLua, Lua, Value};
use yazi_binding::{Composer, ComposerSet};
pub(super) struct Utils;
pub fn compose(
isolate: bool,
) -> Composer<impl Fn(&Lua, &[u8]) -> mlua::Result<Value>, ComposerSet> {
fn get(lua: &Lua, key: &[u8], isolate: bool) -> mlua::Result<Value> {
match key {
// App
b"id" => Utils::id(lua)?,
b"drop" => Utils::drop(lua)?,
b"hide" => Utils::hide(lua)?,
// Cache
b"file_cache" => Utils::file_cache(lua)?,
// Call
b"render" => Utils::render(lua)?,
b"emit" => Utils::emit(lua)?,
b"mgr_emit" => Utils::mgr_emit(lua)?,
// Image
b"image_info" => Utils::image_info(lua)?,
b"image_show" => Utils::image_show(lua)?,
b"image_precache" => Utils::image_precache(lua)?,
// JSON
b"json_encode" => Utils::json_encode(lua)?,
b"json_decode" => Utils::json_decode(lua)?,
// Layout
b"which" => Utils::which(lua)?,
b"input" => Utils::input(lua)?,
b"confirm" => Utils::confirm(lua)?,
b"notify" => Utils::notify(lua)?,
// Log
b"dbg" => Utils::dbg(lua)?,
b"err" => Utils::err(lua)?,
// Preview
b"preview_code" => Utils::preview_code(lua)?,
b"preview_widget" => Utils::preview_widget(lua)?,
// Process
b"proc_info" => Utils::proc_info(lua)?,
// Spot
b"spot_table" => Utils::spot_table(lua)?,
b"spot_widgets" => Utils::spot_widgets(lua)?,
// Sync
b"sync" => Utils::sync(lua, isolate)?,
b"async" => Utils::r#async(lua, isolate)?,
b"chan" => Utils::chan(lua)?,
b"join" => Utils::join(lua)?,
b"select" => Utils::select(lua)?,
// Target
b"target_os" => Utils::target_os(lua)?,
b"target_family" => Utils::target_family(lua)?,
// Text
b"hash" => Utils::hash(lua)?,
b"quote" => Utils::quote(lua)?,
b"truncate" => Utils::truncate(lua)?,
b"clipboard" => Utils::clipboard(lua)?,
// Time
b"time" => Utils::time(lua)?,
b"sleep" => Utils::sleep(lua)?,
// User
#[cfg(unix)]
b"uid" => Utils::uid(lua)?,
#[cfg(unix)]
b"gid" => Utils::gid(lua)?,
#[cfg(unix)]
b"user_name" => Utils::user_name(lua)?,
#[cfg(unix)]
b"group_name" => Utils::group_name(lua)?,
#[cfg(unix)]
b"host_name" => Utils::host_name(lua)?,
_ => return Ok(Value::Nil),
}
.into_lua(lua)
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(move |lua, key| get(lua, key, isolate), set)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/mod.rs | yazi-plugin/src/utils/mod.rs | yazi_macro::mod_flat!(
app cache call image json layer log preview process spot sync target text time user utils
);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/spot.rs | yazi-plugin/src/utils/spot.rs | use mlua::{AnyUserData, Function, Lua, Table};
use yazi_binding::elements::{Edge, Renderable};
use yazi_config::THEME;
use yazi_parser::mgr::{SpotLock, UpdateSpottedOpt};
use yazi_proxy::MgrProxy;
use super::Utils;
impl Utils {
pub(super) fn spot_table(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, (t, table): (mlua::Table, AnyUserData)| {
let mut lock = SpotLock::try_from(t)?;
let mut table = yazi_binding::elements::Table::try_from(table)?;
let area = table.area;
table.area = area.inner(ratatui::widgets::Padding::uniform(1));
lock.data = vec![
Renderable::Clear(yazi_binding::elements::Clear { area }),
Renderable::Border(yazi_binding::elements::Border {
area,
edge: Edge(ratatui::widgets::Borders::ALL),
r#type: ratatui::widgets::BorderType::Rounded,
style: THEME.spot.border.into(),
titles: vec![(
ratatui::widgets::TitlePosition::Top,
ratatui::text::Line::raw("Spot").centered().style(THEME.spot.title),
)],
}),
Renderable::Table(Box::new(table)),
];
MgrProxy::update_spotted(UpdateSpottedOpt { lock });
Ok(())
})
}
pub(super) fn spot_widgets(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, (t, widgets): (Table, Vec<AnyUserData>)| {
let mut lock = SpotLock::try_from(t)?;
lock.data = widgets.into_iter().map(Renderable::try_from).collect::<mlua::Result<_>>()?;
MgrProxy::update_spotted(UpdateSpottedOpt { lock });
Ok(())
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/cache.rs | yazi-plugin/src/utils/cache.rs | use std::hash::Hash;
use mlua::{Function, Lua, Table};
use yazi_binding::{FileRef, Url};
use yazi_config::YAZI;
use yazi_shared::url::UrlLike;
use yazi_shim::Twox128;
use super::Utils;
impl Utils {
pub(super) fn file_cache(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, t: Table| {
let file: FileRef = t.raw_get("file")?;
if file.url.parent() == Some(yazi_shared::url::Url::regular(&YAZI.preview.cache_dir)) {
return Ok(None);
}
let hex = {
let mut h = Twox128::default();
file.hash(&mut h);
t.raw_get("skip").unwrap_or(0usize).hash(&mut h);
format!("{:x}", h.finish_128())
};
Ok(Some(Url::new(YAZI.preview.cache_dir.join(hex))))
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/utils/preview.rs | yazi-plugin/src/utils/preview.rs | use mlua::{AnyUserData, ExternalError, Function, IntoLuaMulti, Lua, Table, Value};
use yazi_binding::{Error, elements::{Area, Renderable, Text}};
use yazi_config::YAZI;
use yazi_fs::FsUrl;
use yazi_parser::mgr::{PreviewLock, UpdatePeekedOpt};
use yazi_proxy::MgrProxy;
use yazi_shared::{errors::PeekError, url::AsUrl};
use super::Utils;
use crate::external::Highlighter;
impl Utils {
pub(super) fn preview_code(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, t: Table| async move {
let area: Area = t.raw_get("area")?;
let mut lock = PreviewLock::try_from(t)?;
let path = lock.url.as_url().unified_path();
let inner = match Highlighter::new(path).highlight(lock.skip, area.size()).await {
Ok(text) => text,
Err(e @ PeekError::Exceed(max)) => return (e.to_string(), max).into_lua_multi(&lua),
Err(e @ PeekError::Unexpected(_)) => {
return e.to_string().into_lua_multi(&lua);
}
};
lock.data = vec![Renderable::Text(Text {
area,
inner,
wrap: YAZI.preview.wrap.into(),
scroll: Default::default(),
})];
MgrProxy::update_peeked(UpdatePeekedOpt { lock });
().into_lua_multi(&lua)
})
}
pub(super) fn preview_widget(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|_, (t, value): (Table, Value)| async move {
let mut lock = PreviewLock::try_from(t)?;
lock.data = match value {
Value::Nil => vec![],
Value::Table(tbl) => tbl
.sequence_values::<AnyUserData>()
.map(|ud| ud.and_then(Renderable::try_from))
.collect::<mlua::Result<_>>()?,
Value::UserData(ud) => match Renderable::try_from(&ud) {
Ok(r) => vec![r],
Err(e) => {
if let Ok(err) = ud.take::<Error>() {
vec![
Renderable::Clear(yazi_binding::elements::Clear { area: lock.area.into() }),
Renderable::from(err).with_area(lock.area),
]
} else {
Err(e)?
}
}
},
_ => Err("preview widget must be a renderable element or a table of them".into_lua_err())?,
};
MgrProxy::update_peeked(UpdatePeekedOpt { lock });
Ok(())
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/elements/mod.rs | yazi-plugin/src/elements/mod.rs | yazi_macro::mod_flat!(elements);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/elements/elements.rs | yazi-plugin/src/elements/elements.rs | use std::borrow::Cow;
use mlua::{AnyUserData, ExternalError, IntoLua, Lua, ObjectLike, Table, Value};
use tracing::error;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use yazi_binding::{Composer, ComposerGet, ComposerSet, Permit, PermitRef, elements::{Line, Rect, Span}, runtime};
use yazi_config::LAYOUT;
use yazi_proxy::{AppProxy, HIDER};
use yazi_shared::replace_to_printable;
pub fn compose() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
match key {
b"area" => area(lua)?,
b"hide" => hide(lua)?,
b"printable" => printable(lua)?,
b"redraw" => redraw(lua)?,
b"render" => render(lua)?,
b"truncate" => truncate(lua)?,
b"width" => width(lua)?,
_ => return Ok(Value::Nil),
}
.into_lua(lua)
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
yazi_binding::elements::compose(get, set)
}
pub(super) fn area(lua: &Lua) -> mlua::Result<Value> {
let f = lua.create_function(|_, s: mlua::String| {
let layout = LAYOUT.get();
Ok(match &*s.as_bytes() {
b"current" => Rect(layout.current),
b"preview" => Rect(layout.preview),
b"progress" => Rect(layout.progress),
_ => Err(format!("unknown area: {}", s.display()).into_lua_err())?,
})
})?;
f.into_lua(lua)
}
pub(super) fn hide(lua: &Lua) -> mlua::Result<Value> {
let f = lua.create_async_function(|lua, ()| async move {
if runtime!(lua)?.initing {
return Err("Cannot call `ui.hide()` during app initialization".into_lua_err());
}
if lua.named_registry_value::<PermitRef>("HIDE_PERMIT").is_ok_and(|h| h.is_some()) {
return Err("Cannot hide while already hidden".into_lua_err());
}
let permit = HIDER.acquire().await.unwrap();
AppProxy::stop().await;
lua.set_named_registry_value("HIDE_PERMIT", Permit::new(permit, AppProxy::resume()))?;
lua.named_registry_value::<AnyUserData>("HIDE_PERMIT")
})?;
f.into_lua(lua)
}
pub(super) fn printable(lua: &Lua) -> mlua::Result<Value> {
let f = lua.create_function(|lua, s: mlua::String| {
Ok(match replace_to_printable(&s.as_bytes(), false, 1, true) {
Cow::Borrowed(_) => s,
Cow::Owned(new) => lua.create_string(&new)?,
})
})?;
f.into_lua(lua)
}
pub(super) fn redraw(lua: &Lua) -> mlua::Result<Value> {
let f = lua.create_function(|lua, c: Table| {
let id: mlua::String = c.get("_id")?;
let mut layout = LAYOUT.get();
match &*id.as_bytes() {
b"current" => layout.current = *c.raw_get::<Rect>("_area")?,
b"preview" => layout.preview = *c.raw_get::<Rect>("_area")?,
b"progress" => layout.progress = *c.raw_get::<Rect>("_area")?,
_ => {}
}
LAYOUT.set(layout);
match c.call_method::<Value>("redraw", ())? {
Value::Table(tbl) => Ok(tbl),
Value::UserData(ud) => lua.create_sequence_from([ud]),
_ => {
error!(
"Failed to `redraw()` the `{}` component: expected a table or UserData",
id.display(),
);
lua.create_table()
}
}
})?;
f.into_lua(lua)
}
pub(super) fn render(lua: &Lua) -> mlua::Result<Value> {
let f = lua.create_function(|_, ()| {
yazi_macro::render!();
Ok(())
})?;
f.into_lua(lua)
}
pub(super) fn truncate(lua: &Lua) -> mlua::Result<Value> {
fn traverse(it: impl Iterator<Item = (usize, char)>, max: usize) -> (Option<usize>, usize, bool) {
let (mut adv, mut last) = (0, 0);
let idx = it
.take_while(|&(_, c)| {
(last, adv) = (adv, adv + c.width().unwrap_or(0));
adv <= max
})
.map(|(i, _)| i)
.last();
(idx, last, adv > max)
}
let f = lua.create_function(|lua, (s, t): (mlua::String, Table)| {
let b = s.as_bytes();
if b.is_empty() {
return Ok(s);
}
let max = t.raw_get("max")?;
if b.len() <= max {
return Ok(s);
} else if max < 1 {
return lua.create_string("");
}
let lossy = String::from_utf8_lossy(&b);
let rtl = t.raw_get("rtl").unwrap_or(false);
let (idx, width, remain) = if rtl {
traverse(lossy.char_indices().rev(), max)
} else {
traverse(lossy.char_indices(), max)
};
let Some(idx) = idx else { return lua.create_string("…") };
if !remain {
return Ok(s);
}
let result: Vec<_> = match (rtl, width == max) {
(false, false) => {
let len = lossy[idx..].chars().next().map_or(0, |c| c.len_utf8());
lossy[..idx + len].bytes().chain("…".bytes()).collect()
}
(false, true) => lossy[..idx].bytes().chain("…".bytes()).collect(),
(true, false) => "…".bytes().chain(lossy[idx..].bytes()).collect(),
(true, true) => {
let len = lossy[idx..].chars().next().map_or(0, |c| c.len_utf8());
"…".bytes().chain(lossy[idx + len..].bytes()).collect()
}
};
lua.create_string(result)
})?;
f.into_lua(lua)
}
pub(super) fn width(lua: &Lua) -> mlua::Result<Value> {
let f = lua.create_function(|_, v: Value| match v {
Value::String(s) => {
let (mut acc, b) = (0, s.as_bytes());
for c in b.utf8_chunks() {
acc += c.valid().width();
if !c.invalid().is_empty() {
acc += 1;
}
}
Ok(acc)
}
Value::UserData(ud) => {
if let Ok(line) = ud.borrow::<Line>() {
Ok(line.width())
} else if let Ok(span) = ud.borrow::<Span>() {
Ok(span.width())
} else {
Err("expected a string, Line, or Span".into_lua_err())?
}
}
_ => Err("expected a string, Line, or Span".into_lua_err())?,
})?;
f.into_lua(lua)
}
#[cfg(test)]
mod tests {
use mlua::{Lua, chunk};
fn truncate(s: &str, max: usize, rtl: bool) -> String {
let lua = Lua::new();
let f = super::truncate(&lua).unwrap();
lua
.load(chunk! {
return $f($s, { max = $max, rtl = $rtl })
})
.call(())
.unwrap()
}
#[test]
fn test_truncate() {
assert_eq!(truncate("你好,world", 0, false), "");
assert_eq!(truncate("你好,world", 1, false), "…");
assert_eq!(truncate("你好,world", 2, false), "…");
assert_eq!(truncate("你好,世界", 3, false), "你…");
assert_eq!(truncate("你好,世界", 4, false), "你…");
assert_eq!(truncate("你好,世界", 5, false), "你好…");
assert_eq!(truncate("Hello, world", 5, false), "Hell…");
assert_eq!(truncate("Ni好,世界", 3, false), "Ni…");
}
#[test]
fn test_truncate_rtl() {
assert_eq!(truncate("world,你好", 0, true), "");
assert_eq!(truncate("world,你好", 1, true), "…");
assert_eq!(truncate("world,你好", 2, true), "…");
assert_eq!(truncate("你好,世界", 3, true), "…界");
assert_eq!(truncate("你好,世界", 4, true), "…界");
assert_eq!(truncate("你好,世界", 5, true), "…世界");
assert_eq!(truncate("Hello, world", 5, true), "…orld");
assert_eq!(truncate("你好,Shi界", 3, true), "…界");
}
#[test]
fn test_truncate_oboe() {
assert_eq!(truncate("Hello, world", 11, false), "Hello, wor…");
assert_eq!(truncate("你好,世界", 9, false), "你好,世…");
assert_eq!(truncate("你好,世Jie", 9, false), "你好,世…");
assert_eq!(truncate("Hello, world", 11, true), "…llo, world");
assert_eq!(truncate("你好,世界", 9, true), "…好,世界");
assert_eq!(truncate("Ni好,世界", 9, true), "…好,世界");
}
#[test]
fn test_truncate_exact() {
assert_eq!(truncate("Hello, world", 12, false), "Hello, world");
assert_eq!(truncate("你好,世界", 10, false), "你好,世界");
assert_eq!(truncate("Hello, world", 12, true), "Hello, world");
assert_eq!(truncate("你好,世界", 10, true), "你好,世界");
}
#[test]
fn test_truncate_overflow() {
assert_eq!(truncate("Hello, world", 13, false), "Hello, world");
assert_eq!(truncate("你好,世界", 11, false), "你好,世界");
assert_eq!(truncate("Hello, world", 13, true), "Hello, world");
assert_eq!(truncate("你好,世界", 11, true), "你好,世界");
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/range.rs | yazi-plugin/src/bindings/range.rs | use mlua::{IntoLua, Lua};
pub struct Range<T>(std::ops::Range<T>);
impl<T> From<std::ops::Range<T>> for Range<T> {
fn from(value: std::ops::Range<T>) -> Self { Self(value) }
}
impl<T> IntoLua for Range<T>
where
T: IntoLua,
{
fn into_lua(self, lua: &Lua) -> mlua::Result<mlua::Value> {
lua.create_sequence_from([self.0.start, self.0.end])?.into_lua(lua)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/chan.rs | yazi-plugin/src/bindings/chan.rs | use mlua::{ExternalError, IntoLuaMulti, UserData, Value};
use yazi_binding::Error;
pub struct MpscTx(pub tokio::sync::mpsc::Sender<Value>);
pub struct MpscRx(pub tokio::sync::mpsc::Receiver<Value>);
impl UserData for MpscTx {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method("send", |lua, me, value: Value| async move {
match me.0.send(value).await {
Ok(()) => true.into_lua_multi(&lua),
Err(e) => (false, Error::custom(e.to_string())).into_lua_multi(&lua),
}
});
}
}
impl UserData for MpscRx {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method_mut("recv", |lua, mut me, ()| async move {
match me.0.recv().await {
Some(value) => (value, true).into_lua_multi(&lua),
None => (Value::Nil, false).into_lua_multi(&lua),
}
});
}
}
pub struct MpscUnboundedTx(pub tokio::sync::mpsc::UnboundedSender<Value>);
pub struct MpscUnboundedRx(pub tokio::sync::mpsc::UnboundedReceiver<Value>);
impl UserData for MpscUnboundedTx {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_method("send", |lua, me, value: Value| match me.0.send(value) {
Ok(()) => true.into_lua_multi(lua),
Err(e) => (false, Error::custom(e.to_string())).into_lua_multi(lua),
});
}
}
impl UserData for MpscUnboundedRx {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method_mut("recv", |lua, mut me, ()| async move {
match me.0.recv().await {
Some(value) => (value, true).into_lua_multi(&lua),
None => (Value::Nil, false).into_lua_multi(&lua),
}
});
}
}
pub struct OneshotTx(pub Option<tokio::sync::oneshot::Sender<Value>>);
pub struct OneshotRx(pub Option<tokio::sync::oneshot::Receiver<Value>>);
impl UserData for OneshotTx {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_method_mut("send", |lua, me, value: Value| {
let Some(tx) = me.0.take() else {
return Err("Oneshot sender already used".into_lua_err());
};
match tx.send(value) {
Ok(()) => true.into_lua_multi(lua),
Err(_) => (false, Error::custom("Oneshot receiver closed")).into_lua_multi(lua),
}
});
}
}
impl UserData for OneshotRx {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method_mut("recv", |lua, mut me, ()| async move {
let Some(rx) = me.0.take() else {
return Err("Oneshot receiver already used".into_lua_err());
};
match rx.await {
Ok(value) => value.into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::custom(e.to_string())).into_lua_multi(&lua),
}
});
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/image.rs | yazi-plugin/src/bindings/image.rs | use std::ops::Deref;
use mlua::{MetaMethod, UserData};
pub struct ImageInfo(yazi_adapter::ImageInfo);
impl Deref for ImageInfo {
type Target = yazi_adapter::ImageInfo;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl From<yazi_adapter::ImageInfo> for ImageInfo {
fn from(value: yazi_adapter::ImageInfo) -> Self { Self(value) }
}
impl UserData for ImageInfo {
fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("w", |_, me| Ok(me.width));
fields.add_field_method_get("h", |_, me| Ok(me.height));
fields.add_field_method_get("ori", |_, me| Ok(me.orientation.map(|o| o.to_exif())));
fields.add_field_method_get("format", |_, me| Ok(ImageFormat(me.format)));
fields.add_field_method_get("color", |_, me| Ok(ImageColor(me.color)));
}
}
// --- ImageFormat
struct ImageFormat(yazi_adapter::ImageFormat);
impl UserData for ImageFormat {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::ToString, |_, me, ()| {
use yazi_adapter::ImageFormat as F;
Ok(match me.0 {
F::Png => "PNG",
F::Jpeg => "JPEG",
F::Gif => "GIF",
F::WebP => "WEBP",
F::Pnm => "PNM",
F::Tiff => "TIFF",
F::Tga => "TGA",
F::Dds => "DDS",
F::Bmp => "BMP",
F::Ico => "ICO",
F::Hdr => "HDR",
F::OpenExr => "OpenEXR",
F::Farbfeld => "Farbfeld",
F::Avif => "AVIF",
F::Qoi => "QOI",
_ => "Unknown",
})
});
}
}
// --- ImageColor
struct ImageColor(yazi_adapter::ImageColor);
impl UserData for ImageColor {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::ToString, |_, me, ()| {
use yazi_adapter::ImageColor as C;
Ok(match me.0 {
C::L8 => "L8",
C::La8 => "La8",
C::Rgb8 => "Rgb8",
C::Rgba8 => "Rgba8",
C::L16 => "L16",
C::La16 => "La16",
C::Rgb16 => "Rgb16",
C::Rgba16 => "Rgba16",
C::Rgb32F => "Rgb32F",
C::Rgba32F => "Rgba32F",
_ => "Unknown",
})
});
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/mouse.rs | yazi-plugin/src/bindings/mouse.rs | use std::ops::Deref;
use crossterm::event::MouseButton;
use mlua::{UserData, UserDataFields};
#[derive(Clone, Copy)]
pub struct MouseEvent(crossterm::event::MouseEvent);
impl Deref for MouseEvent {
type Target = crossterm::event::MouseEvent;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl From<crossterm::event::MouseEvent> for MouseEvent {
fn from(event: crossterm::event::MouseEvent) -> Self { Self(event) }
}
impl UserData for MouseEvent {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("x", |_, me| Ok(me.column));
fields.add_field_method_get("y", |_, me| Ok(me.row));
fields.add_field_method_get("is_left", |_, me| {
use crossterm::event::MouseEventKind as K;
Ok(matches!(me.kind, K::Down(b) | K::Up(b) | K::Drag(b) if b == MouseButton::Left))
});
fields.add_field_method_get("is_right", |_, me| {
use crossterm::event::MouseEventKind as K;
Ok(matches!(me.kind, K::Down(b) | K::Up(b) | K::Drag(b) if b == MouseButton::Right))
});
fields.add_field_method_get("is_middle", |_, me| {
use crossterm::event::MouseEventKind as K;
Ok(matches!(me.kind, K::Down(b) | K::Up(b) | K::Drag(b) if b == MouseButton::Middle))
});
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/layer.rs | yazi-plugin/src/bindings/layer.rs | use mlua::{MetaMethod, UserData};
#[derive(Clone, Copy)]
pub struct Layer(yazi_shared::Layer);
impl From<yazi_shared::Layer> for Layer {
fn from(event: yazi_shared::Layer) -> Self { Self(event) }
}
impl UserData for Layer {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::ToString, |_, me, ()| Ok(me.0.to_string()));
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/mod.rs | yazi-plugin/src/bindings/mod.rs | yazi_macro::mod_flat!(calculator chan image input layer mouse range);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/calculator.rs | yazi-plugin/src/bindings/calculator.rs | use mlua::{IntoLuaMulti, UserData, UserDataMethods, Value};
use yazi_binding::Error;
pub enum SizeCalculator {
Local(yazi_fs::provider::local::SizeCalculator),
Remote(yazi_vfs::provider::SizeCalculator),
}
impl UserData for SizeCalculator {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method_mut("recv", |lua, mut me, ()| async move {
let next = match &mut *me {
Self::Local(it) => it.next().await,
Self::Remote(it) => it.next().await,
};
match next {
Ok(value) => value.into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
});
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/bindings/input.rs | yazi-plugin/src/bindings/input.rs | use std::pin::Pin;
use mlua::{UserData, prelude::LuaUserDataMethods};
use tokio::pin;
use tokio_stream::StreamExt;
use yazi_shared::errors::InputError;
pub struct InputRx<T: StreamExt<Item = Result<String, InputError>>> {
inner: T,
}
impl<T: StreamExt<Item = Result<String, InputError>>> InputRx<T> {
pub fn new(inner: T) -> Self { Self { inner } }
pub async fn consume(inner: T) -> (Option<String>, u8) {
pin!(inner);
inner.next().await.map(Self::parse).unwrap_or((None, 0))
}
fn parse(res: Result<String, InputError>) -> (Option<String>, u8) {
match res {
Ok(s) => (Some(s), 1),
Err(InputError::Canceled(s)) => (Some(s), 2),
Err(InputError::Typed(s)) => (Some(s), 3),
_ => (None, 0),
}
}
}
impl<T: StreamExt<Item = Result<String, InputError>> + 'static> UserData for InputRx<T> {
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method_mut("recv", |_, mut me, ()| async move {
let mut inner = unsafe { Pin::new_unchecked(&mut me.inner) };
Ok(inner.next().await.map(Self::parse).unwrap_or((None, 0)))
});
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/theme/theme.rs | yazi-plugin/src/theme/theme.rs | use mlua::{IntoLua, Lua, Value};
use yazi_binding::{Composer, ComposerGet, ComposerSet, Style, Url, deprecate};
use yazi_config::THEME;
pub fn compose() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
match key {
b"app" => app(),
b"mgr" => mgr(),
b"tabs" => tabs(),
b"mode" => mode(),
b"indicator" => indicator(),
b"status" => status(),
b"which" => which(),
b"confirm" => confirm(),
b"spot" => spot(),
b"notify" => notify(),
b"pick" => pick(),
b"input" => input(),
b"cmp" => cmp(),
b"tasks" => tasks(),
b"help" => help(),
_ => return Ok(Value::Nil),
}
.into_lua(lua)
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn app() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let a = &THEME.app;
match key {
b"overall" => Style::from(a.overall).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn mgr() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let m = &THEME.mgr;
match key {
b"cwd" => Style::from(m.cwd).into_lua(lua),
b"hovered" => {
deprecate!(
lua,
"`th.mgr.hovered` is deprecated, use `th.indicator.current` instead, in your {}\nSee #3419 for more details: https://github.com/sxyazi/yazi/pull/3419"
);
Style::from(THEME.indicator.current).into_lua(lua)
}
b"preview_hovered" => {
deprecate!(
lua,
"`th.mgr.preview_hovered` is deprecated, use `th.indicator.preview` instead, in your {}\nSee #3419 for more details: https://github.com/sxyazi/yazi/pull/3419"
);
Style::from(THEME.indicator.preview).into_lua(lua)
}
b"find_keyword" => Style::from(m.find_keyword).into_lua(lua),
b"find_position" => Style::from(m.find_position).into_lua(lua),
b"symlink_target" => Style::from(m.symlink_target).into_lua(lua),
b"marker_copied" => Style::from(m.marker_copied).into_lua(lua),
b"marker_cut" => Style::from(m.marker_cut).into_lua(lua),
b"marker_marked" => Style::from(m.marker_marked).into_lua(lua),
b"marker_selected" => Style::from(m.marker_selected).into_lua(lua),
b"count_copied" => Style::from(m.count_copied).into_lua(lua),
b"count_cut" => Style::from(m.count_cut).into_lua(lua),
b"count_selected" => Style::from(m.count_selected).into_lua(lua),
b"border_symbol" => lua.create_string(&m.border_symbol)?.into_lua(lua),
b"border_style" => Style::from(m.border_style).into_lua(lua),
b"syntect_theme" => Url::new(&m.syntect_theme).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn tabs() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.tabs;
match key {
b"active" => Style::from(t.active).into_lua(lua),
b"inactive" => Style::from(t.inactive).into_lua(lua),
b"sep_inner" => lua
.create_table_from([
("open", lua.create_string(&t.sep_inner.open)?),
("close", lua.create_string(&t.sep_inner.close)?),
])?
.into_lua(lua),
b"sep_outer" => lua
.create_table_from([
("open", lua.create_string(&t.sep_outer.open)?),
("close", lua.create_string(&t.sep_outer.close)?),
])?
.into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn mode() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.mode;
match key {
b"normal_main" => Style::from(t.normal_main).into_lua(lua),
b"normal_alt" => Style::from(t.normal_alt).into_lua(lua),
b"select_main" => Style::from(t.select_main).into_lua(lua),
b"select_alt" => Style::from(t.select_alt).into_lua(lua),
b"unset_main" => Style::from(t.unset_main).into_lua(lua),
b"unset_alt" => Style::from(t.unset_alt).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn indicator() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.indicator;
match key {
b"parent" => Style::from(t.parent).into_lua(lua),
b"current" => Style::from(t.current).into_lua(lua),
b"preview" => Style::from(t.preview).into_lua(lua),
b"padding" => lua
.create_table_from([
("open", lua.create_string(&t.padding.open)?),
("close", lua.create_string(&t.padding.close)?),
])?
.into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn status() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.status;
match key {
b"overall" => Style::from(t.overall).into_lua(lua),
b"sep_left" => lua
.create_table_from([
("open", lua.create_string(&t.sep_left.open)?),
("close", lua.create_string(&t.sep_left.close)?),
])?
.into_lua(lua),
b"sep_right" => lua
.create_table_from([
("open", lua.create_string(&t.sep_right.open)?),
("close", lua.create_string(&t.sep_right.close)?),
])?
.into_lua(lua),
b"perm_sep" => Style::from(t.perm_sep).into_lua(lua),
b"perm_type" => Style::from(t.perm_type).into_lua(lua),
b"perm_read" => Style::from(t.perm_read).into_lua(lua),
b"perm_write" => Style::from(t.perm_write).into_lua(lua),
b"perm_exec" => Style::from(t.perm_exec).into_lua(lua),
b"progress_label" => Style::from(t.progress_label).into_lua(lua),
b"progress_normal" => Style::from(t.progress_normal).into_lua(lua),
b"progress_error" => Style::from(t.progress_error).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn which() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.which;
match key {
b"cols" => t.cols.into_lua(lua),
b"mask" => Style::from(t.mask).into_lua(lua),
b"cand" => Style::from(t.cand).into_lua(lua),
b"rest" => Style::from(t.rest).into_lua(lua),
b"desc" => Style::from(t.desc).into_lua(lua),
b"separator" => lua.create_string(&t.separator)?.into_lua(lua),
b"separator_style" => Style::from(t.separator_style).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn confirm() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.confirm;
match key {
b"border" => Style::from(t.border).into_lua(lua),
b"title" => Style::from(t.title).into_lua(lua),
b"body" => Style::from(t.body).into_lua(lua),
b"list" => Style::from(t.list).into_lua(lua),
b"btn_yes" => Style::from(t.btn_yes).into_lua(lua),
b"btn_no" => Style::from(t.btn_no).into_lua(lua),
b"btn_labels" => lua
.create_sequence_from([
lua.create_string(&t.btn_labels[0])?,
lua.create_string(&t.btn_labels[1])?,
])?
.into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn spot() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.spot;
match key {
b"border" => Style::from(t.border).into_lua(lua),
b"title" => Style::from(t.title).into_lua(lua),
b"tbl_col" => Style::from(t.tbl_col).into_lua(lua),
b"tbl_cell" => Style::from(t.tbl_cell).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn notify() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.notify;
match key {
b"title_info" => Style::from(t.title_info).into_lua(lua),
b"title_warn" => Style::from(t.title_warn).into_lua(lua),
b"title_error" => Style::from(t.title_error).into_lua(lua),
b"icon_info" => lua.create_string(&t.icon_info)?.into_lua(lua),
b"icon_warn" => lua.create_string(&t.icon_warn)?.into_lua(lua),
b"icon_error" => lua.create_string(&t.icon_error)?.into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn pick() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.pick;
match key {
b"border" => Style::from(t.border).into_lua(lua),
b"active" => Style::from(t.active).into_lua(lua),
b"inactive" => Style::from(t.inactive).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn input() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.input;
match key {
b"border" => Style::from(t.border).into_lua(lua),
b"title" => Style::from(t.title).into_lua(lua),
b"value" => Style::from(t.value).into_lua(lua),
b"selected" => Style::from(t.selected).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn cmp() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.cmp;
match key {
b"border" => Style::from(t.border).into_lua(lua),
b"active" => Style::from(t.active).into_lua(lua),
b"inactive" => Style::from(t.inactive).into_lua(lua),
b"icon_file" => lua.create_string(&t.icon_file)?.into_lua(lua),
b"icon_folder" => lua.create_string(&t.icon_folder)?.into_lua(lua),
b"icon_command" => lua.create_string(&t.icon_command)?.into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn tasks() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.tasks;
match key {
b"border" => Style::from(t.border).into_lua(lua),
b"title" => Style::from(t.title).into_lua(lua),
b"hovered" => Style::from(t.hovered).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn help() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
let t = &THEME.help;
match key {
b"on" => Style::from(t.on).into_lua(lua),
b"run" => Style::from(t.run).into_lua(lua),
b"desc" => Style::from(t.desc).into_lua(lua),
b"hovered" => Style::from(t.hovered).into_lua(lua),
b"footer" => Style::from(t.footer).into_lua(lua),
_ => Ok(Value::Nil),
}
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/theme/mod.rs | yazi-plugin/src/theme/mod.rs | yazi_macro::mod_flat!(theme);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/preload.rs | yazi-plugin/src/isolate/preload.rs | use mlua::{ExternalError, ExternalResult, HookTriggers, IntoLua, ObjectLike, VmState};
use tokio::{runtime::Handle, select};
use tokio_util::sync::CancellationToken;
use yazi_binding::{Error, File, elements::Rect};
use yazi_config::LAYOUT;
use yazi_dds::Sendable;
use yazi_shared::event::Cmd;
use super::slim_lua;
use crate::loader::LOADER;
pub async fn preload(
cmd: &'static Cmd,
file: yazi_fs::File,
ct: CancellationToken,
) -> mlua::Result<(bool, Option<Error>)> {
let ct_ = ct.clone();
tokio::task::spawn_blocking(move || {
let future = async {
LOADER.ensure(&cmd.name, |_| ()).await.into_lua_err()?;
let lua = slim_lua(&cmd.name)?;
lua.set_hook(
HookTriggers::new().on_calls().on_returns().every_nth_instruction(2000),
move |_, dbg| {
if ct.is_cancelled() && dbg.source().what != "C" {
Err("Preload task cancelled".into_lua_err())
} else {
Ok(VmState::Continue)
}
},
)?;
let plugin = LOADER.load_once(&lua, &cmd.name)?;
let job = lua.create_table_from([
("area", Rect::from(LAYOUT.get().preview).into_lua(&lua)?),
("args", Sendable::args_to_table_ref(&lua, &cmd.args)?.into_lua(&lua)?),
("file", File::new(file).into_lua(&lua)?),
("skip", 0.into_lua(&lua)?),
])?;
if ct_.is_cancelled() {
Ok((false, None))
} else {
plugin.call_async_method("preload", job).await
}
};
Handle::current().block_on(async {
select! {
_ = ct_.cancelled() => Ok((false, None)),
r = future => match r {
Err(e) if e.to_string().contains("Preload task cancelled") => Ok((false, None)),
Ok(_) | Err(_) => r,
},
}
})
})
.await
.into_lua_err()?
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/peek.rs | yazi-plugin/src/isolate/peek.rs | use mlua::{ExternalError, HookTriggers, IntoLua, ObjectLike, VmState};
use tokio::{runtime::Handle, select};
use tokio_util::sync::CancellationToken;
use tracing::error;
use yazi_binding::{Error, File, elements::{Rect, Renderable}};
use yazi_config::LAYOUT;
use yazi_dds::Sendable;
use yazi_parser::{app::{PluginCallback, PluginOpt}, mgr::{PreviewLock, UpdatePeekedOpt}};
use yazi_proxy::{AppProxy, MgrProxy};
use yazi_shared::{event::Cmd, pool::Symbol};
use super::slim_lua;
use crate::loader::{LOADER, Loader};
pub fn peek(
cmd: &'static Cmd,
file: yazi_fs::File,
mime: Symbol<str>,
skip: usize,
) -> Option<CancellationToken> {
let (id, ..) = Loader::normalize_id(&cmd.name).ok()?;
let ct = CancellationToken::new();
if let Some(c) = LOADER.read().get(id) {
if let Err(e) = Loader::compatible_or_error(id, c) {
peek_error(file, mime, skip, e);
return None;
} else if c.sync_peek {
peek_sync(cmd, file, mime, skip);
} else {
peek_async(cmd, file, mime, skip, ct.clone());
}
return Some(ct).filter(|_| !c.sync_peek);
}
let ct_ = ct.clone();
tokio::spawn(async move {
select! {
_ = ct_.cancelled() => {},
Ok(b) = LOADER.ensure(id, |c| c.sync_peek) => {
if b {
peek_sync(cmd, file, mime, skip);
} else {
peek_async(cmd, file, mime, skip, ct_);
}
},
else => {}
}
});
Some(ct)
}
fn peek_sync(cmd: &'static Cmd, file: yazi_fs::File, mime: Symbol<str>, skip: usize) {
let cb: PluginCallback = Box::new(move |lua, plugin| {
let job = lua.create_table_from([
("area", Rect::from(LAYOUT.get().preview).into_lua(lua)?),
("args", Sendable::args_to_table_ref(lua, &cmd.args)?.into_lua(lua)?),
("file", File::new(file).into_lua(lua)?),
("mime", mime.into_lua(lua)?),
("skip", skip.into_lua(lua)?),
])?;
plugin.call_method("peek", job)
});
AppProxy::plugin(PluginOpt::new_callback(&*cmd.name, cb));
}
fn peek_async(
cmd: &'static Cmd,
file: yazi_fs::File,
mime: Symbol<str>,
skip: usize,
ct: CancellationToken,
) {
let ct_ = ct.clone();
tokio::task::spawn_blocking(move || {
let future = async {
let lua = slim_lua(&cmd.name)?;
lua.set_hook(
HookTriggers::new().on_calls().on_returns().every_nth_instruction(2000),
move |_, dbg| {
if ct.is_cancelled() && dbg.source().what != "C" {
Err("Peek task cancelled".into_lua_err())
} else {
Ok(VmState::Continue)
}
},
)?;
let plugin = LOADER.load_once(&lua, &cmd.name)?;
let job = lua.create_table_from([
("area", Rect::from(LAYOUT.get().preview).into_lua(&lua)?),
("args", Sendable::args_to_table_ref(&lua, &cmd.args)?.into_lua(&lua)?),
("file", File::new(file).into_lua(&lua)?),
("mime", mime.into_lua(&lua)?),
("skip", skip.into_lua(&lua)?),
])?;
if ct_.is_cancelled() { Ok(()) } else { plugin.call_async_method("peek", job).await }
};
let result = Handle::current().block_on(async {
select! {
_ = ct_.cancelled() => Ok(()),
r = future => r,
}
});
if let Err(e) = result
&& !e.to_string().contains("Peek task cancelled")
{
error!("{e}");
}
});
}
fn peek_error(file: yazi_fs::File, mime: Symbol<str>, skip: usize, error: anyhow::Error) {
let area = LAYOUT.get().preview;
MgrProxy::update_peeked(UpdatePeekedOpt {
lock: PreviewLock {
url: file.url,
cha: file.cha,
mime: mime.to_string(),
skip,
area: area.into(),
data: vec![
Renderable::Clear(yazi_binding::elements::Clear { area: area.into() }),
Renderable::from(Error::custom(error.to_string())).with_area(area),
],
},
});
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/fetch.rs | yazi-plugin/src/isolate/fetch.rs | use mlua::{ExternalResult, FromLua, IntoLua, Lua, ObjectLike, Value};
use tokio::runtime::Handle;
use yazi_binding::{Error, File};
use yazi_dds::Sendable;
use yazi_shared::event::CmdCow;
use super::slim_lua;
use crate::loader::LOADER;
pub async fn fetch(
cmd: CmdCow,
files: Vec<yazi_fs::File>,
) -> mlua::Result<(FetchState, Option<Error>)> {
if files.is_empty() {
return Ok((FetchState::Bool(true), None));
}
LOADER.ensure(&cmd.name, |_| ()).await.into_lua_err()?;
tokio::task::spawn_blocking(move || {
let lua = slim_lua(&cmd.name)?;
let plugin = LOADER.load_once(&lua, &cmd.name)?;
Handle::current().block_on(plugin.call_async_method(
"fetch",
lua.create_table_from([
("args", Sendable::args_to_table_ref(&lua, &cmd.args)?.into_lua(&lua)?),
("files", lua.create_sequence_from(files.into_iter().map(File::new))?.into_lua(&lua)?),
])?,
))
})
.await
.into_lua_err()?
}
// --- State
pub enum FetchState {
Bool(bool),
Vec(Vec<bool>),
}
impl FetchState {
#[inline]
pub fn get(&self, idx: usize) -> bool {
match self {
Self::Bool(b) => *b,
Self::Vec(v) => v.get(idx).copied().unwrap_or(false),
}
}
}
impl FromLua for FetchState {
fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> {
Ok(match value {
Value::Boolean(b) => Self::Bool(b),
Value::Table(tbl) => Self::Vec(tbl.sequence_values().collect::<mlua::Result<_>>()?),
_ => Err(mlua::Error::FromLuaConversionError {
from: value.type_name(),
to: "FetchState".to_owned(),
message: Some("expected a boolean or a table of booleans".to_owned()),
})?,
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/mod.rs | yazi-plugin/src/isolate/mod.rs | yazi_macro::mod_flat!(entry fetch isolate peek preload seek spot);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/isolate.rs | yazi-plugin/src/isolate/isolate.rs | use mlua::{IntoLua, Lua};
use yazi_binding::Runtime;
use yazi_macro::plugin_preset as preset;
pub fn slim_lua(name: &str) -> mlua::Result<Lua> {
let lua = Lua::new();
lua.set_app_data(Runtime::new_isolate(name));
// Base
let globals = lua.globals();
globals.raw_set("ui", crate::elements::compose())?;
globals.raw_set("ya", crate::utils::compose(true))?;
globals.raw_set("fs", crate::fs::compose())?;
globals.raw_set("rt", crate::runtime::compose())?;
globals.raw_set("th", crate::theme::compose().into_lua(&lua)?)?;
yazi_binding::Cha::install(&lua)?;
yazi_binding::File::install(&lua)?;
yazi_binding::Url::install(&lua)?;
yazi_binding::Error::install(&lua)?;
crate::loader::install(&lua)?;
crate::process::install(&lua)?;
// Addons
lua.load(preset!("ya")).set_name("ya.lua").exec()?;
Ok(lua)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/spot.rs | yazi-plugin/src/isolate/spot.rs | use mlua::{ExternalError, ExternalResult, HookTriggers, IntoLua, ObjectLike, VmState};
use tokio::{runtime::Handle, select};
use tokio_util::sync::CancellationToken;
use tracing::error;
use yazi_binding::{File, Id};
use yazi_dds::Sendable;
use yazi_shared::{Ids, event::Cmd, pool::Symbol};
use super::slim_lua;
use crate::loader::LOADER;
static IDS: Ids = Ids::new();
pub fn spot(
cmd: &'static Cmd,
file: yazi_fs::File,
mime: Symbol<str>,
skip: usize,
) -> CancellationToken {
let ct = CancellationToken::new();
let (ct1, ct2) = (ct.clone(), ct.clone());
tokio::task::spawn_blocking(move || {
let future = async {
LOADER.ensure(&cmd.name, |_| ()).await.into_lua_err()?;
let lua = slim_lua(&cmd.name)?;
lua.set_hook(
HookTriggers::new().on_calls().on_returns().every_nth_instruction(2000),
move |_, dbg| {
if ct1.is_cancelled() && dbg.source().what != "C" {
Err("Spot task cancelled".into_lua_err())
} else {
Ok(VmState::Continue)
}
},
)?;
let plugin = LOADER.load_once(&lua, &cmd.name)?;
let job = lua.create_table_from([
("id", Id(IDS.next()).into_lua(&lua)?),
("args", Sendable::args_to_table_ref(&lua, &cmd.args)?.into_lua(&lua)?),
("file", File::new(file).into_lua(&lua)?),
("mime", mime.into_lua(&lua)?),
("skip", skip.into_lua(&lua)?),
])?;
if ct2.is_cancelled() { Ok(()) } else { plugin.call_async_method("spot", job).await }
};
Handle::current().block_on(async {
select! {
_ = ct2.cancelled() => {},
Err(e) = future => if !e.to_string().contains("Spot task cancelled") {
error!("{e}");
},
else => {}
}
});
});
ct
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/seek.rs | yazi-plugin/src/isolate/seek.rs | use mlua::{IntoLua, ObjectLike};
use yazi_binding::{File, elements::Rect};
use yazi_config::LAYOUT;
use yazi_parser::app::{PluginCallback, PluginOpt};
use yazi_proxy::AppProxy;
use yazi_shared::event::Cmd;
pub fn seek_sync(cmd: &'static Cmd, file: yazi_fs::File, units: i16) {
let cb: PluginCallback = Box::new(move |lua, plugin| {
let job = lua.create_table_from([
("file", File::new(file).into_lua(lua)?),
("area", Rect::from(LAYOUT.get().preview).into_lua(lua)?),
("units", units.into_lua(lua)?),
])?;
plugin.call_method("seek", job)
});
AppProxy::plugin(PluginOpt::new_callback(&*cmd.name, cb));
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/isolate/entry.rs | yazi-plugin/src/isolate/entry.rs | use mlua::{ExternalResult, ObjectLike};
use tokio::runtime::Handle;
use yazi_dds::Sendable;
use yazi_parser::app::PluginOpt;
use super::slim_lua;
use crate::loader::LOADER;
pub async fn entry(opt: PluginOpt) -> mlua::Result<()> {
LOADER.ensure(&opt.id, |_| ()).await.into_lua_err()?;
tokio::task::spawn_blocking(move || {
let lua = slim_lua(&opt.id)?;
let plugin = LOADER.load_once(&lua, &opt.id)?;
let job = lua.create_table_from([("args", Sendable::args_to_table(&lua, opt.args)?)])?;
Handle::current().block_on(plugin.call_async_method("entry", job))
})
.await
.into_lua_err()?
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/fs/op.rs | yazi-plugin/src/fs/op.rs | use mlua::{IntoLua, Lua, Table};
use yazi_binding::{Cha, File, Id, Path, Url};
pub(super) struct FilesOp(yazi_fs::FilesOp);
impl FilesOp {
pub(super) fn part(_: &Lua, t: Table) -> mlua::Result<Self> {
let id: Id = t.raw_get("id")?;
let url: Url = t.raw_get("url")?;
let files: Table = t.raw_get("files")?;
Ok(Self(yazi_fs::FilesOp::Part(
url.into(),
files
.sequence_values::<File>()
.map(|f| f.map(Into::into))
.collect::<mlua::Result<Vec<_>>>()?,
*id,
)))
}
pub(super) fn done(_: &Lua, t: Table) -> mlua::Result<Self> {
let id: Id = t.raw_get("id")?;
let cha: Cha = t.raw_get("cha")?;
let url: Url = t.raw_get("url")?;
Ok(Self(yazi_fs::FilesOp::Done(url.into(), *cha, *id)))
}
pub(super) fn size(_: &Lua, t: Table) -> mlua::Result<Self> {
let url: Url = t.raw_get("url")?;
let sizes: Table = t.raw_get("sizes")?;
Ok(Self(yazi_fs::FilesOp::Size(
url.into(),
sizes
.pairs::<Path, u64>()
.map(|r| r.map(|(urn, size)| (urn.into(), size)))
.collect::<mlua::Result<_>>()?,
)))
}
}
impl IntoLua for FilesOp {
fn into_lua(self, lua: &Lua) -> mlua::Result<mlua::Value> {
lua.create_any_userdata(self.0)?.into_lua(lua)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/fs/fs.rs | yazi-plugin/src/fs/fs.rs | use std::str::FromStr;
use mlua::{ExternalError, Function, IntoLua, IntoLuaMulti, Lua, Table, Value};
use yazi_binding::{Cha, Composer, ComposerGet, ComposerSet, Error, File, Url, UrlRef};
use yazi_config::Pattern;
use yazi_fs::{mounts::PARTITIONS, provider::{Attrs, DirReader, FileHolder}};
use yazi_shared::url::{UrlCow, UrlLike};
use yazi_vfs::{VfsFile, provider};
use crate::bindings::SizeCalculator;
pub fn compose() -> Composer<ComposerGet, ComposerSet> {
fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> {
match key {
b"op" => op(lua)?,
b"cwd" => cwd(lua)?,
b"cha" => cha(lua)?,
b"copy" => copy(lua)?,
b"write" => write(lua)?,
b"create" => create(lua)?,
b"remove" => remove(lua)?,
b"rename" => rename(lua)?,
b"read_dir" => read_dir(lua)?,
b"calc_size" => calc_size(lua)?,
b"expand_url" => expand_url(lua)?,
b"unique_name" => unique_name(lua)?,
b"partitions" => partitions(lua)?,
_ => return Ok(Value::Nil),
}
.into_lua(lua)
}
fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) }
Composer::new(get, set)
}
fn op(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, (name, t): (mlua::String, Table)| match &*name.as_bytes() {
b"part" => super::FilesOp::part(lua, t),
b"done" => super::FilesOp::done(lua, t),
b"size" => super::FilesOp::size(lua, t),
_ => Err("Unknown operation".into_lua_err())?,
})
}
fn cwd(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, ()| match std::env::current_dir() {
Ok(p) => Url::new(p).into_lua_multi(lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(lua),
})
}
fn cha(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (url, follow): (UrlRef, Option<bool>)| async move {
let cha = if follow.unwrap_or(false) {
provider::metadata(&*url).await
} else {
provider::symlink_metadata(&*url).await
};
match cha {
Ok(c) => Cha(c).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn copy(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (from, to): (UrlRef, UrlRef)| async move {
match provider::copy(&*from, &*to, Attrs::default()).await {
Ok(len) => len.into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn write(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (url, data): (UrlRef, mlua::String)| async move {
match provider::write(&*url, data.as_bytes()).await {
Ok(()) => true.into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn create(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (r#type, url): (mlua::String, UrlRef)| async move {
let result = match &*r#type.as_bytes() {
b"dir" => provider::create_dir(&*url).await,
b"dir_all" => provider::create_dir_all(&*url).await,
_ => Err("Creation type must be 'dir' or 'dir_all'".into_lua_err())?,
};
match result {
Ok(()) => true.into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn remove(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (r#type, url): (mlua::String, UrlRef)| async move {
let result = match &*r#type.as_bytes() {
b"file" => provider::remove_file(&*url).await,
b"dir" => provider::remove_dir(&*url).await,
b"dir_all" => provider::remove_dir_all(&*url).await,
b"dir_clean" => provider::remove_dir_clean(&*url).await,
_ => Err("Removal type must be 'file', 'dir', 'dir_all', or 'dir_clean'".into_lua_err())?,
};
match result {
Ok(()) => true.into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn rename(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (from, to): (UrlRef, UrlRef)| async move {
match provider::rename(&*from, &*to).await {
Ok(()) => true.into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn read_dir(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (dir, options): (UrlRef, Table)| async move {
let pat = if let Ok(s) = options.raw_get::<mlua::String>("glob") {
Some(Pattern::from_str(&s.to_str()?)?)
} else {
None
};
let limit = options.raw_get("limit").unwrap_or(usize::MAX);
let resolve = options.raw_get("resolve").unwrap_or(false);
let mut it = match provider::read_dir(&*dir).await {
Ok(it) => it,
Err(e) => return (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
};
let mut files = vec![];
while let Ok(Some(next)) = it.next().await {
let url = next.url();
if pat.as_ref().is_some_and(|p| !p.match_url(&url, p.is_dir)) {
continue;
}
let file = if !resolve {
yazi_fs::File::from_dummy(url, next.file_type().await.ok())
} else if let Ok(cha) = next.metadata().await {
yazi_fs::File::from_follow(url, cha).await
} else {
yazi_fs::File::from_dummy(url, next.file_type().await.ok())
};
files.push(File::new(file));
if files.len() == limit {
break;
}
}
lua.create_sequence_from(files)?.into_lua_multi(&lua)
})
}
fn calc_size(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, url: UrlRef| async move {
let it = if let Some(path) = url.as_local() {
yazi_fs::provider::local::SizeCalculator::new(path).await.map(SizeCalculator::Local)
} else {
yazi_vfs::provider::SizeCalculator::new(&*url).await.map(SizeCalculator::Remote)
};
match it {
Ok(it) => it.into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
})
}
#[allow(irrefutable_let_patterns)]
fn expand_url(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, value: Value| {
use yazi_fs::path::expand_url;
match &value {
Value::String(s) => Url::new(expand_url(UrlCow::try_from(&*s.as_bytes())?)).into_lua(lua),
Value::UserData(ud) => {
if let u = expand_url(&*ud.borrow::<yazi_binding::Url>()?)
&& u.is_owned()
{
Url::new(u.into_owned()).into_lua(lua)
} else {
Ok(value)
}
}
_ => Err("must be a string or a Url".into_lua_err())?,
}
})
}
fn unique_name(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, url: UrlRef| async move {
match yazi_vfs::unique_name(url.clone(), async { false }).await {
Ok(u) => Url::new(u).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn partitions(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, ()| async move {
PARTITIONS
.read()
.iter()
.filter(|&p| !p.systemic())
.map(|p| {
lua.create_table_from([
("src", p.src.clone().into_lua(&lua)?),
("dist", p.dist.clone().into_lua(&lua)?),
("label", p.label.clone().into_lua(&lua)?),
("fstype", p.fstype.clone().into_lua(&lua)?),
("external", p.external.into_lua(&lua)?),
("removable", p.removable.into_lua(&lua)?),
])
})
.collect::<mlua::Result<Vec<Table>>>()
})
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-plugin/src/fs/mod.rs | yazi-plugin/src/fs/mod.rs | yazi_macro::mod_flat!(fs op);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/lib.rs | yazi-widgets/src/lib.rs | yazi_macro::mod_pub!(input);
yazi_macro::mod_flat!(clipboard scrollable);
pub fn init() { CLIPBOARD.with(<_>::default); }
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/scrollable.rs | yazi-widgets/src/scrollable.rs | use yazi_parser::Step;
pub trait Scrollable {
fn total(&self) -> usize;
fn limit(&self) -> usize;
fn scrolloff(&self) -> usize { self.limit() / 2 }
fn cursor_mut(&mut self) -> &mut usize;
fn offset_mut(&mut self) -> &mut usize;
fn scroll(&mut self, step: impl Into<Step>) -> bool {
let new = step.into().add(*self.cursor_mut(), self.total(), self.limit());
if new > *self.cursor_mut() { self.next(new) } else { self.prev(new) }
}
fn next(&mut self, n_cur: usize) -> bool {
let (o_cur, o_off) = (*self.cursor_mut(), *self.offset_mut());
let (total, limit, scrolloff) = (self.total(), self.limit(), self.scrolloff());
let n_off = if n_cur < total.min(o_off + limit).saturating_sub(scrolloff) {
o_off.min(total.saturating_sub(1))
} else {
total.saturating_sub(limit).min(o_off + n_cur - o_cur)
};
*self.cursor_mut() = n_cur;
*self.offset_mut() = n_off;
(n_cur, n_off) != (o_cur, o_off)
}
fn prev(&mut self, n_cur: usize) -> bool {
let (o_cur, o_off) = (*self.cursor_mut(), *self.offset_mut());
let n_off = if n_cur < o_off + self.scrolloff() {
o_off.saturating_sub(o_cur - n_cur)
} else {
self.total().saturating_sub(1).min(o_off)
};
*self.cursor_mut() = n_cur;
*self.offset_mut() = n_off;
(n_cur, n_off) != (o_cur, o_off)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/clipboard.rs | yazi-widgets/src/clipboard.rs | use parking_lot::Mutex;
use yazi_shared::RoCell;
pub static CLIPBOARD: RoCell<Clipboard> = RoCell::new();
#[derive(Default)]
pub struct Clipboard {
content: Mutex<Vec<u8>>,
}
impl Clipboard {
#[cfg(unix)]
pub async fn get(&self) -> Vec<u8> {
use tokio::process::Command;
use yazi_shared::in_ssh_connection;
if in_ssh_connection() {
return self.content.lock().clone();
}
let all = [
("pbpaste", &[][..]),
("termux-clipboard-get", &[]),
("wl-paste", &["-n"]),
("xclip", &["-o", "-selection", "clipboard"]),
("xsel", &["-ob"]),
];
for (bin, args) in all {
let Ok(output) = Command::new(bin).args(args).kill_on_drop(true).output().await else {
continue;
};
if output.status.success() {
return output.stdout;
}
}
self.content.lock().clone()
}
#[cfg(windows)]
pub async fn get(&self) -> Vec<u8> {
use clipboard_win::get_clipboard_string;
let result = tokio::task::spawn_blocking(get_clipboard_string);
if let Ok(Ok(s)) = result.await {
return s.into_bytes();
}
self.content.lock().clone()
}
#[cfg(unix)]
pub async fn set(&self, s: impl AsRef<[u8]>) {
use std::process::Stdio;
use crossterm::execute;
use tokio::{io::AsyncWriteExt, process::Command};
use yazi_term::tty::TTY;
s.as_ref().clone_into(&mut self.content.lock());
execute!(TTY.writer(), osc52::SetClipboard::new(s.as_ref())).ok();
let all = [
("pbcopy", &[][..]),
("termux-clipboard-set", &[]),
("wl-copy", &[]),
("xclip", &["-selection", "clipboard"]),
("xsel", &["-ib"]),
];
for (bin, args) in all {
let cmd = Command::new(bin)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn();
let Ok(mut child) = cmd else { continue };
let mut stdin = child.stdin.take().unwrap();
if stdin.write_all(s.as_ref()).await.is_err() {
continue;
}
drop(stdin);
if child.wait().await.map(|s| s.success()).unwrap_or_default() {
break;
}
}
}
#[cfg(windows)]
pub async fn set(&self, s: impl AsRef<[u8]>) {
use clipboard_win::set_clipboard_string;
let b = s.as_ref().to_owned();
*self.content.lock() = b.clone();
tokio::task::spawn_blocking(move || set_clipboard_string(&String::from_utf8_lossy(&b)))
.await
.ok();
}
}
#[cfg(unix)]
mod osc52 {
use base64::{Engine, engine::general_purpose};
#[derive(Debug)]
pub struct SetClipboard {
content: String,
}
impl SetClipboard {
pub fn new(content: &[u8]) -> Self {
Self { content: general_purpose::STANDARD.encode(content) }
}
}
impl crossterm::Command for SetClipboard {
fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result {
write!(f, "\x1b]52;c;{}\x1b\\", self.content)
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/op.rs | yazi-widgets/src/input/op.rs | use std::ops::Range;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InputOp {
#[default]
None,
Select(usize),
Delete(bool, bool, usize), // cut, insert, start
Yank(usize),
}
impl InputOp {
#[inline]
pub(super) fn start(&self) -> Option<usize> {
match self {
Self::None => None,
Self::Select(s) => Some(*s),
Self::Delete(.., s) => Some(*s),
Self::Yank(s) => Some(*s),
}
}
#[inline]
pub(super) fn range(&self, cursor: usize, include: bool) -> Option<Range<usize>> {
self
.start()
.map(|s| if s <= cursor { (s, cursor) } else { (cursor, s) })
.map(|(s, e)| s..e + include as usize)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/widget.rs | yazi-widgets/src/input/widget.rs | use std::ops::Range;
use ratatui::{layout::Rect, text::Line, widgets::Widget};
use yazi_config::THEME;
use super::Input;
impl Widget for &Input {
fn render(self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer)
where
Self: Sized,
{
yazi_binding::elements::Clear::default().render(area, buf);
Line::styled(self.display(), THEME.input.value).render(area, buf);
if let Some(Range { start, end }) = self.selected() {
let s = start.min(area.width);
buf.set_style(
Rect {
x: area.x + s,
y: area.y,
width: (end - start).min(area.width - s),
height: area.height.min(1),
},
THEME.input.selected,
);
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/mod.rs | yazi-widgets/src/input/mod.rs | yazi_macro::mod_pub!(commands);
yazi_macro::mod_flat!(input mode op snap snaps widget);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/snaps.rs | yazi-widgets/src/input/snaps.rs | use std::mem;
use super::InputSnap;
#[derive(PartialEq, Eq)]
pub struct InputSnaps {
idx: usize,
versions: Vec<InputSnap>,
current: InputSnap,
}
impl Default for InputSnaps {
fn default() -> Self {
Self {
idx: 0,
versions: vec![InputSnap::new(String::new(), false, 0)],
current: InputSnap::new(String::new(), false, 0),
}
}
}
impl InputSnaps {
pub fn new(value: String, obscure: bool, limit: usize) -> Self {
let current = InputSnap::new(value, obscure, limit);
Self { idx: 0, versions: vec![current.clone()], current }
}
pub(super) fn tag(&mut self, limit: usize) -> bool {
if self.versions.len() <= self.idx {
return false;
}
// Sync *current* cursor position to the *last* version:
// Save offset/cursor/ect. of the *current* as the last version,
// while keeping the *last* value unchanged.
let value = mem::take(&mut self.versions[self.idx].value);
self.versions[self.idx] = self.current.clone();
self.versions[self.idx].value = value;
self.versions[self.idx].resize(limit);
// If the *current* value is the same as the *last* version
if self.versions[self.idx].value == self.current.value {
return false;
}
self.versions.truncate(self.idx + 1);
self.versions.push(self.current().clone());
self.idx += 1;
true
}
pub(super) fn undo(&mut self) -> bool {
if self.idx == 0 {
return false;
}
self.idx -= 1;
self.current = self.versions[self.idx].clone();
true
}
pub(super) fn redo(&mut self) -> bool {
if self.idx + 1 >= self.versions.len() {
return false;
}
self.idx += 1;
self.current = self.versions[self.idx].clone();
true
}
}
impl InputSnaps {
#[inline]
pub fn current(&self) -> &InputSnap { &self.current }
#[inline]
pub(super) fn current_mut(&mut self) -> &mut InputSnap { &mut self.current }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/mode.rs | yazi-widgets/src/input/mode.rs | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InputMode {
Normal,
#[default]
Insert,
Replace,
}
impl InputMode {
#[inline]
pub(super) fn delta(&self) -> usize { (*self != Self::Insert) as usize }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/snap.rs | yazi-widgets/src/input/snap.rs | use std::ops::Range;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use super::{InputMode, InputOp};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InputSnap {
pub value: String,
pub op: InputOp,
pub mode: InputMode,
pub obscure: bool,
pub offset: usize,
pub cursor: usize,
}
impl InputSnap {
pub(super) fn new(value: String, obscure: bool, limit: usize) -> Self {
let mut snap = Self {
value,
op: Default::default(),
mode: Default::default(),
obscure,
offset: 0,
cursor: usize::MAX,
};
snap.resize(limit);
snap
}
#[inline]
pub(super) fn resize(&mut self, limit: usize) {
let count = self.count();
let limit = if self.obscure {
count.min(limit)
} else {
Self::find_window(self.value.chars().rev(), 0, limit).end
};
self.cursor = self.cursor.min(self.count().saturating_sub(self.mode.delta()));
self.offset = if self.cursor < (self.offset + limit).min(count) {
count.saturating_sub(limit).min(self.offset)
} else {
count.saturating_sub(limit).min(self.cursor.saturating_sub(limit) + 1)
};
}
}
impl InputSnap {
#[inline]
pub(super) fn len(&self) -> usize { self.value.len() }
#[inline]
pub(super) fn count(&self) -> usize { self.value.chars().count() }
#[inline]
pub(super) fn idx(&self, n: usize) -> Option<usize> {
self
.value
.char_indices()
.nth(n)
.map(|(i, _)| i)
.or_else(|| if n == self.count() { Some(self.len()) } else { None })
}
#[inline]
pub(super) fn slice(&self, range: Range<usize>) -> &str {
let (s, e) = (self.idx(range.start), self.idx(range.end));
&self.value[s.unwrap()..e.unwrap()]
}
#[inline]
pub(super) fn width(&self, range: Range<usize>) -> u16 {
if self.obscure { range.len() as u16 } else { self.slice(range).width() as u16 }
}
#[inline]
pub(super) fn window(&self, limit: usize) -> Range<usize> {
Self::find_window(
self.value.chars().map(|c| if self.obscure { '•' } else { c }),
self.offset,
limit,
)
}
pub(super) fn find_window<T>(it: T, offset: usize, limit: usize) -> Range<usize>
where
T: Iterator<Item = char>,
{
let mut width = 0;
let mut range = None;
for (i, c) in it.enumerate().skip(offset) {
width += c.width().unwrap_or(0);
if width > limit {
break;
}
match range {
None => range = Some(i..i + 1),
Some(ref mut r) => r.end = i + 1,
}
}
range.unwrap_or(0..0)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/input.rs | yazi-widgets/src/input/input.rs | use std::{borrow::Cow, ops::Range};
use crossterm::cursor::SetCursorStyle;
use yazi_config::YAZI;
use super::{InputSnap, InputSnaps, mode::InputMode, op::InputOp};
use crate::CLIPBOARD;
pub type InputCallback = Box<dyn Fn(&str, &str)>;
#[derive(Default)]
pub struct Input {
pub snaps: InputSnaps,
pub limit: usize,
pub obscure: bool,
pub callback: Option<InputCallback>,
}
impl Input {
pub fn new(value: String, limit: usize, obscure: bool, callback: InputCallback) -> Self {
Self { snaps: InputSnaps::new(value, obscure, limit), limit, obscure, callback: Some(callback) }
}
pub(super) fn handle_op(&mut self, cursor: usize, include: bool) -> bool {
let old = self.snap().clone();
let snap = self.snap_mut();
match snap.op {
InputOp::None | InputOp::Select(_) => {
snap.cursor = cursor;
}
InputOp::Delete(cut, insert, _) => {
let range = snap.op.range(cursor, include).unwrap();
let Range { start, end } = snap.idx(range.start)..snap.idx(range.end);
let drain = snap.value.drain(start.unwrap()..end.unwrap()).collect::<String>();
if cut {
futures::executor::block_on(CLIPBOARD.set(&drain));
}
snap.op = InputOp::None;
snap.mode = if insert { InputMode::Insert } else { InputMode::Normal };
snap.cursor = range.start;
}
InputOp::Yank(_) => {
let range = snap.op.range(cursor, include).unwrap();
let Range { start, end } = snap.idx(range.start)..snap.idx(range.end);
let yanked = &snap.value[start.unwrap()..end.unwrap()];
snap.op = InputOp::None;
futures::executor::block_on(CLIPBOARD.set(yanked));
}
};
snap.cursor = snap.count().saturating_sub(snap.mode.delta()).min(snap.cursor);
if snap == &old {
return false;
}
if !matches!(old.op, InputOp::None | InputOp::Select(_)) {
self.snaps.tag(self.limit).then(|| self.flush_value());
}
true
}
pub(super) fn flush_value(&mut self) {
if let Some(cb) = &self.callback {
let (before, after) = self.partition();
cb(before, after);
}
}
}
impl Input {
#[inline]
pub fn value(&self) -> &str { &self.snap().value }
#[inline]
pub fn display(&self) -> Cow<'_, str> {
if self.obscure {
"•".repeat(self.snap().window(self.limit).len()).into()
} else {
self.snap().slice(self.snap().window(self.limit)).into()
}
}
#[inline]
pub fn mode(&self) -> InputMode { self.snap().mode }
#[inline]
pub fn cursor(&self) -> u16 { self.snap().width(self.snap().offset..self.snap().cursor) }
pub fn cursor_shape(&self) -> SetCursorStyle {
use InputMode as M;
match self.mode() {
M::Normal if YAZI.input.cursor_blink => SetCursorStyle::BlinkingBlock,
M::Normal if !YAZI.input.cursor_blink => SetCursorStyle::SteadyBlock,
M::Insert if YAZI.input.cursor_blink => SetCursorStyle::BlinkingBar,
M::Insert if !YAZI.input.cursor_blink => SetCursorStyle::SteadyBar,
M::Replace if YAZI.input.cursor_blink => SetCursorStyle::BlinkingUnderScore,
M::Replace if !YAZI.input.cursor_blink => SetCursorStyle::SteadyUnderScore,
M::Normal | M::Insert | M::Replace => unreachable!(),
}
}
pub fn selected(&self) -> Option<Range<u16>> {
let snap = self.snap();
let start = snap.op.start()?;
let (start, end) =
if start < snap.cursor { (start, snap.cursor) } else { (snap.cursor + 1, start + 1) };
let win = snap.window(self.limit);
let Range { start, end } = start.max(win.start)..end.min(win.end);
let s = snap.width(snap.offset..start);
Some(s..s + snap.width(start..end))
}
#[inline]
pub fn partition(&self) -> (&str, &str) {
let snap = self.snap();
let idx = snap.idx(snap.cursor).unwrap();
(&snap.value[..idx], &snap.value[idx..])
}
#[inline]
pub fn snap(&self) -> &InputSnap { self.snaps.current() }
#[inline]
pub fn snap_mut(&mut self) -> &mut InputSnap { self.snaps.current_mut() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/complete.rs | yazi-widgets/src/input/commands/complete.rs | use std::path::MAIN_SEPARATOR_STR;
use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::CompleteOpt;
use yazi_shared::data::Data;
use crate::input::Input;
#[cfg(windows)]
const SEPARATOR: [char; 2] = ['/', '\\'];
#[cfg(not(windows))]
const SEPARATOR: char = std::path::MAIN_SEPARATOR;
impl Input {
pub fn complete(&mut self, opt: CompleteOpt) -> Result<Data> {
let (before, after) = self.partition();
let new = if let Some((prefix, _)) = before.rsplit_once(SEPARATOR) {
format!("{prefix}/{}{after}", opt.item.completable()).replace(SEPARATOR, MAIN_SEPARATOR_STR)
} else {
format!("{}{after}", opt.item.completable()).replace(SEPARATOR, MAIN_SEPARATOR_STR)
};
let snap = self.snap_mut();
if new == snap.value {
succ!();
}
let delta = new.chars().count() as isize - snap.count() as isize;
snap.value = new;
act!(r#move, self, delta)?;
self.flush_value();
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/move.rs | yazi-widgets/src/input/commands/move.rs | use anyhow::Result;
use yazi_macro::{render, succ};
use yazi_parser::input::MoveOpt;
use yazi_shared::data::Data;
use crate::input::{Input, op::InputOp, snap::InputSnap};
impl Input {
pub fn r#move(&mut self, opt: MoveOpt) -> Result<Data> {
let snap = self.snap();
if opt.in_operating && snap.op == InputOp::None {
succ!();
}
let o_cur = snap.cursor;
render!(self.handle_op(opt.step.add(&snap.value, snap.cursor), false));
let n_cur = self.snap().cursor;
let (limit, snap) = (self.limit, self.snap_mut());
if snap.value.is_empty() {
succ!(snap.offset = 0);
}
let (o_off, scrolloff) = (snap.offset, 5.min(limit / 2));
snap.offset = if n_cur <= o_cur {
let it = snap.slice(0..n_cur).chars().rev().map(|c| if snap.obscure { '•' } else { c });
let pad = InputSnap::find_window(it, 0, scrolloff).end;
if n_cur >= o_off { snap.offset.min(n_cur - pad) } else { n_cur - pad }
} else {
let count = snap.count();
let it = snap.slice(n_cur..count).chars().map(|c| if snap.obscure { '•' } else { c });
let pad = InputSnap::find_window(it, 0, scrolloff + snap.mode.delta()).end;
let it = snap.slice(0..n_cur + pad).chars().rev().map(|c| if snap.obscure { '•' } else { c });
let max = InputSnap::find_window(it, 0, limit).end;
if snap.width(o_off..n_cur) < limit as u16 {
snap.offset.max(n_cur + pad - max)
} else {
n_cur + pad - max
}
};
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/casefy.rs | yazi-widgets/src/input/commands/casefy.rs | use std::ops::Range;
use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::CasefyOpt;
use yazi_shared::data::Data;
use crate::input::{Input, op::InputOp};
impl Input {
pub fn casefy(&mut self, opt: CasefyOpt) -> Result<Data> {
let snap = self.snap_mut();
if !matches!(snap.op, InputOp::Select(_)) {
succ!();
}
let range = snap.op.range(snap.cursor, true).unwrap();
let Range { start, end } = snap.idx(range.start)..snap.idx(range.end);
let (start, end) = (start.unwrap(), end.unwrap());
let casefied = opt.transform(&snap.value[start..end]);
snap.value.replace_range(start..end, &casefied);
snap.op = InputOp::None;
snap.cursor = range.start;
self.snaps.tag(self.limit).then(|| self.flush_value());
act!(r#move, self)?;
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/insert.rs | yazi-widgets/src/input/commands/insert.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::InsertOpt;
use yazi_shared::data::Data;
use crate::input::{Input, InputMode, op::InputOp};
impl Input {
pub fn insert(&mut self, opt: InsertOpt) -> Result<Data> {
let snap = self.snap_mut();
if snap.mode == InputMode::Normal {
snap.op = InputOp::None;
snap.mode = InputMode::Insert;
} else {
succ!();
}
if opt.append {
act!(r#move, self, 1)?;
}
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/yank.rs | yazi-widgets/src/input/commands/yank.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::VoidOpt;
use yazi_shared::data::Data;
use crate::input::{Input, op::InputOp};
impl Input {
pub fn yank(&mut self, _: VoidOpt) -> Result<Data> {
match self.snap().op {
InputOp::None => {
self.snap_mut().op = InputOp::Yank(self.snap().cursor);
}
InputOp::Select(start) => {
self.snap_mut().op = InputOp::Yank(start);
render!(self.handle_op(self.snap().cursor, true));
act!(r#move, self)?;
}
InputOp::Yank(_) => {
self.snap_mut().op = InputOp::Yank(0);
act!(r#move, self, self.snap().len() as isize)?;
}
_ => {}
}
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/visual.rs | yazi-widgets/src/input/commands/visual.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::VoidOpt;
use yazi_shared::data::Data;
use crate::input::{Input, InputMode, op::InputOp};
impl Input {
pub fn visual(&mut self, _: VoidOpt) -> Result<Data> {
if self.snap().mode != InputMode::Normal {
act!(escape, self)?;
}
let snap = self.snap_mut();
if let InputOp::Select(_) = snap.op {
succ!();
}
if !snap.value.is_empty() {
snap.op = InputOp::Select(snap.cursor);
render!();
}
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/kill.rs | yazi-widgets/src/input/commands/kill.rs | use std::ops::RangeBounds;
use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::KillOpt;
use yazi_shared::{CharKind, data::Data};
use crate::input::Input;
impl Input {
pub fn kill(&mut self, opt: KillOpt) -> Result<Data> {
let snap = self.snap_mut();
match opt.kind.as_ref() {
"all" => self.kill_range(..),
"bol" => {
let end = snap.idx(snap.cursor).unwrap_or(snap.len());
self.kill_range(..end)
}
"eol" => {
let start = snap.idx(snap.cursor).unwrap_or(snap.len());
self.kill_range(start..)
}
"backward" => {
let end = snap.idx(snap.cursor).unwrap_or(snap.len());
let start = end - Self::find_word_boundary(snap.value[..end].chars().rev());
self.kill_range(start..end)
}
"forward" => {
let start = snap.idx(snap.cursor).unwrap_or(snap.len());
let end = start + Self::find_word_boundary(snap.value[start..].chars());
self.kill_range(start..end)
}
_ => succ!(),
}
}
fn kill_range(&mut self, range: impl RangeBounds<usize>) -> Result<Data> {
let snap = self.snap_mut();
snap.cursor = match range.start_bound() {
std::ops::Bound::Included(i) => *i,
std::ops::Bound::Excluded(_) => unreachable!(),
std::ops::Bound::Unbounded => 0,
};
if snap.value.drain(range).next().is_none() {
succ!();
}
act!(r#move, self)?;
self.flush_value();
succ!(render!());
}
/// Searches for a word boundary and returns the movement in the cursor
/// position.
///
/// A word boundary is where the [`CharKind`] changes.
///
/// If `skip_whitespace_first` is true, we skip initial whitespace.
/// Otherwise, we skip whitespace after reaching a word boundary.
///
/// If `stop_before_boundary` is true, returns how many characters the cursor
/// needs to move to be at the character *BEFORE* the word boundary, or until
/// the end of the iterator.
///
/// Otherwise, returns how many characters to move to reach right *AFTER* the
/// word boundary, or the end of the iterator.
fn find_word_boundary(input: impl Iterator<Item = char> + Clone) -> usize {
fn count_spaces(input: impl Iterator<Item = char>) -> usize {
// Move until we don't see any more whitespace.
input.take_while(|&c| CharKind::new(c) == CharKind::Space).count()
}
fn count_characters(mut input: impl Iterator<Item = char>) -> usize {
// Determine the current character class.
let first = match input.next() {
Some(c) => CharKind::new(c),
None => return 0,
};
// Move until we see a different character class or the end of the iterator.
input.take_while(|&c| CharKind::new(c) == first).count() + 1
}
let n = count_spaces(input.clone());
let n = n + count_characters(input.clone().skip(n));
input.take(n).fold(0, |acc, c| acc + c.len_utf8())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/backspace.rs | yazi-widgets/src/input/commands/backspace.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::BackspaceOpt;
use yazi_shared::data::Data;
use crate::input::Input;
impl Input {
pub fn backspace(&mut self, opt: BackspaceOpt) -> Result<Data> {
let snap = self.snap_mut();
if !opt.under && snap.cursor < 1 {
succ!();
} else if opt.under && snap.cursor >= snap.count() {
succ!();
}
if opt.under {
snap.value.remove(snap.idx(snap.cursor).unwrap());
act!(r#move, self)?;
} else {
snap.value.remove(snap.idx(snap.cursor - 1).unwrap());
act!(r#move, self, -1)?;
}
self.flush_value();
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/replace.rs | yazi-widgets/src/input/commands/replace.rs | use anyhow::Result;
use yazi_macro::{render, succ};
use yazi_parser::VoidOpt;
use yazi_shared::{data::Data, replace_cow};
use crate::input::{Input, InputMode, op::InputOp};
impl Input {
pub fn replace(&mut self, _: VoidOpt) -> Result<Data> {
let snap = self.snap_mut();
if snap.mode == InputMode::Normal {
snap.op = InputOp::None;
snap.mode = InputMode::Replace;
render!();
}
succ!();
}
pub fn replace_str(&mut self, s: &str) -> Result<Data> {
let s = replace_cow(replace_cow(s, "\r", " "), "\n", " ");
let snap = self.snap_mut();
snap.mode = InputMode::Normal;
let start = snap.idx(snap.cursor).unwrap();
let mut it = snap.value[start..].char_indices();
match (it.next(), it.next()) {
(None, _) => {}
(Some(_), None) => snap.value.replace_range(start..snap.len(), &s),
(Some(_), Some((len, _))) => snap.value.replace_range(start..start + len, &s),
}
self.snaps.tag(self.limit).then(|| self.flush_value());
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/type.rs | yazi-widgets/src/input/commands/type.rs | use anyhow::Result;
use yazi_config::keymap::Key;
use yazi_macro::{act, render, succ};
use yazi_shared::{data::Data, replace_cow};
use crate::input::{Input, InputMode};
impl Input {
pub fn r#type(&mut self, key: &Key) -> Result<bool> {
let Some(c) = key.plain() else { return Ok(false) };
if self.mode() == InputMode::Insert {
self.type_str(c.encode_utf8(&mut [0; 4]))?;
return Ok(true);
} else if self.mode() == InputMode::Replace {
self.replace_str(c.encode_utf8(&mut [0; 4]))?;
return Ok(true);
}
Ok(false)
}
pub fn type_str(&mut self, s: &str) -> Result<Data> {
let s = replace_cow(replace_cow(s, "\r", " "), "\n", " ");
let snap = self.snap_mut();
if snap.cursor < 1 {
snap.value.insert_str(0, &s);
} else {
snap.value.insert_str(snap.idx(snap.cursor).unwrap(), &s);
}
act!(r#move, self, s.chars().count() as isize)?;
self.flush_value();
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/paste.rs | yazi-widgets/src/input/commands/paste.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::PasteOpt;
use yazi_shared::data::Data;
use crate::{CLIPBOARD, input::{Input, op::InputOp}};
impl Input {
pub fn paste(&mut self, opt: PasteOpt) -> Result<Data> {
if let Some(start) = self.snap().op.start() {
self.snap_mut().op = InputOp::Delete(false, false, start);
self.handle_op(self.snap().cursor, true);
}
let s = futures::executor::block_on(CLIPBOARD.get());
if s.is_empty() {
succ!();
}
act!(insert, self, !opt.before)?;
self.type_str(&String::from_utf8_lossy(&s))?;
act!(escape, self)?;
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/undo.rs | yazi-widgets/src/input/commands/undo.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::VoidOpt;
use yazi_shared::data::Data;
use crate::input::{Input, InputMode, InputOp};
impl Input {
pub fn undo(&mut self, _: VoidOpt) -> Result<Data> {
if self.snap().op != InputOp::None {
succ!();
}
if !self.snaps.undo() {
succ!();
}
act!(r#move, self)?;
if self.snap().mode == InputMode::Insert {
act!(escape, self)?;
}
succ!(render!());
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/commands.rs | yazi-widgets/src/input/commands/commands.rs | use anyhow::Result;
use yazi_macro::{act, succ};
use yazi_shared::{data::Data, event::CmdCow};
use crate::input::{Input, InputMode};
impl Input {
pub fn execute(&mut self, cmd: CmdCow) -> Result<Data> {
macro_rules! on {
($name:ident) => {
if cmd.name == stringify!($name) {
return act!($name, self, cmd);
}
};
($name:ident, $alias:literal) => {
if cmd.name == $alias {
return act!($name, self, cmd);
}
};
}
on!(r#move, "move");
on!(backward);
on!(forward);
match self.mode() {
InputMode::Normal => {
on!(insert);
on!(visual);
on!(replace);
on!(delete);
on!(yank);
on!(paste);
on!(undo);
on!(redo);
on!(casefy);
}
InputMode::Insert => {
on!(visual);
on!(backspace);
on!(kill);
}
InputMode::Replace => {}
}
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/mod.rs | yazi-widgets/src/input/commands/mod.rs | yazi_macro::mod_flat!(backspace backward casefy commands complete delete escape forward insert kill paste r#move r#type redo replace undo visual yank);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/backward.rs | yazi-widgets/src/input/commands/backward.rs | use anyhow::Result;
use yazi_macro::{act, succ};
use yazi_parser::input::BackwardOpt;
use yazi_shared::{CharKind, data::Data};
use crate::input::Input;
impl Input {
pub fn backward(&mut self, opt: BackwardOpt) -> Result<Data> {
let snap = self.snap();
if snap.cursor == 0 {
return act!(r#move, self);
}
let idx = snap.idx(snap.cursor).unwrap_or(snap.len());
let mut it = snap.value[..idx].chars().rev().enumerate();
let mut prev = CharKind::new(it.next().unwrap().1);
for (i, c) in it {
let k = CharKind::new(c);
if prev != CharKind::Space && prev.vary(k, opt.far) {
return act!(r#move, self, -(i as isize));
}
prev = k;
}
if prev != CharKind::Space {
act!(r#move, self, -(snap.len() as isize))?;
}
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/redo.rs | yazi-widgets/src/input/commands/redo.rs | use anyhow::Result;
use yazi_macro::{act, render};
use yazi_parser::VoidOpt;
use yazi_shared::data::Data;
use crate::input::Input;
impl Input {
pub fn redo(&mut self, _: VoidOpt) -> Result<Data> {
render!(self.snaps.redo());
act!(r#move, self)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/escape.rs | yazi-widgets/src/input/commands/escape.rs | use anyhow::Result;
use yazi_macro::{act, succ};
use yazi_parser::VoidOpt;
use yazi_shared::data::Data;
use crate::input::{Input, InputMode, op::InputOp};
impl Input {
pub fn escape(&mut self, _: VoidOpt) -> Result<Data> {
let snap = self.snap_mut();
match snap.mode {
InputMode::Normal => {
snap.op = InputOp::None;
}
InputMode::Insert => {
snap.mode = InputMode::Normal;
act!(r#move, self, -1)?;
}
InputMode::Replace => {
snap.mode = InputMode::Normal;
}
}
self.snaps.tag(self.limit);
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/forward.rs | yazi-widgets/src/input/commands/forward.rs | use anyhow::Result;
use yazi_macro::act;
use yazi_parser::input::ForwardOpt;
use yazi_shared::{CharKind, data::Data};
use crate::input::{Input, op::InputOp};
impl Input {
pub fn forward(&mut self, opt: ForwardOpt) -> Result<Data> {
let snap = self.snap();
let mut it = snap.value.chars().skip(snap.cursor).enumerate();
let Some(mut prev) = it.next().map(|(_, c)| CharKind::new(c)) else {
return act!(r#move, self);
};
for (i, c) in it {
let k = CharKind::new(c);
let b = if opt.end_of_word {
prev != CharKind::Space && prev.vary(k, opt.far) && i != 1
} else {
k != CharKind::Space && k.vary(prev, opt.far)
};
if b && !matches!(snap.op, InputOp::None | InputOp::Select(_)) {
return act!(r#move, self, i as isize);
} else if b {
return act!(
r#move,
self,
if opt.end_of_word { i - snap.mode.delta() } else { i } as isize
);
}
prev = k;
}
act!(r#move, self, snap.len() as isize)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-widgets/src/input/commands/delete.rs | yazi-widgets/src/input/commands/delete.rs | use anyhow::Result;
use yazi_macro::{act, render, succ};
use yazi_parser::input::DeleteOpt;
use yazi_shared::data::Data;
use crate::input::{Input, op::InputOp};
impl Input {
pub fn delete(&mut self, opt: DeleteOpt) -> Result<Data> {
match self.snap().op {
InputOp::None => {
self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, self.snap().cursor);
}
InputOp::Select(start) => {
self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, start);
render!(self.handle_op(self.snap().cursor, true));
act!(r#move, self)?;
}
InputOp::Delete(..) => {
self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, 0);
act!(r#move, self, self.snap().len() as isize)?;
}
_ => {}
}
succ!();
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/op.rs | yazi-vfs/src/op.rs | use yazi_fs::FilesOp;
use yazi_shared::url::{UrlBuf, UrlLike};
use crate::maybe_exists;
pub trait VfsFilesOp {
fn issue_error(cwd: &UrlBuf, kind: impl Into<yazi_fs::error::Error>) -> impl Future<Output = ()>;
}
impl VfsFilesOp for FilesOp {
async fn issue_error(cwd: &UrlBuf, err: impl Into<yazi_fs::error::Error>) {
let err = err.into();
if err.kind() != std::io::ErrorKind::NotFound {
Self::IOErr(cwd.clone(), err).emit();
} else if maybe_exists(cwd).await {
Self::IOErr(cwd.clone(), err).emit();
} else if let Some((p, n)) = cwd.pair() {
Self::Deleting(p.into(), [n.into()].into()).emit();
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/lib.rs | yazi-vfs/src/lib.rs | yazi_macro::mod_pub!(provider);
yazi_macro::mod_flat!(cha file files fns op);
pub fn init() { provider::init(); }
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/file.rs | yazi-vfs/src/file.rs | use anyhow::Result;
use yazi_fs::{File, cha::Cha};
use yazi_shared::url::{UrlBuf, UrlCow};
use crate::{VfsCha, provider};
pub trait VfsFile: Sized {
fn new<'a>(url: impl Into<UrlCow<'a>>) -> impl Future<Output = Result<Self>>;
fn from_follow(url: UrlBuf, cha: Cha) -> impl Future<Output = Self>;
}
impl VfsFile for File {
#[inline]
async fn new<'a>(url: impl Into<UrlCow<'a>>) -> Result<Self> {
let url = url.into();
let cha = provider::symlink_metadata(&url).await?;
Ok(Self::from_follow(url.into_owned(), cha).await)
}
#[inline]
async fn from_follow(url: UrlBuf, cha: Cha) -> Self {
let link_to = if cha.is_link() { provider::read_link(&url).await.ok() } else { None };
let cha = Cha::from_follow(&url, cha).await;
Self { url, cha, link_to }
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/files.rs | yazi-vfs/src/files.rs | use std::io;
use tokio::{select, sync::mpsc::{self, UnboundedReceiver}};
use yazi_fs::{File, Files, FilesOp, cha::Cha, mounts::PARTITIONS, provider::{DirReader, FileHolder}};
use yazi_shared::url::UrlBuf;
use crate::{VfsCha, VfsFile, VfsFilesOp, provider::{self, DirEntry}};
pub trait VfsFiles {
fn from_dir(dir: &UrlBuf) -> impl Future<Output = io::Result<UnboundedReceiver<File>>>;
fn from_dir_bulk(dir: &UrlBuf) -> impl Future<Output = io::Result<Vec<File>>>;
fn assert_stale(dir: &UrlBuf, cha: Cha) -> impl Future<Output = Option<Cha>>;
}
impl VfsFiles for Files {
async fn from_dir(dir: &UrlBuf) -> std::io::Result<UnboundedReceiver<File>> {
let mut it = provider::read_dir(dir).await?;
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
while let Ok(Some(ent)) = it.next().await {
select! {
_ = tx.closed() => break,
result = ent.metadata() => {
let url = ent.url();
_ = tx.send(match result {
Ok(cha) => File::from_follow(url, cha).await,
Err(_) => File::from_dummy(url, ent.file_type().await.ok())
});
}
}
}
});
Ok(rx)
}
async fn from_dir_bulk(dir: &UrlBuf) -> std::io::Result<Vec<File>> {
let mut it = provider::read_dir(dir).await?;
let mut entries = Vec::new();
while let Ok(Some(entry)) = it.next().await {
entries.push(entry);
}
let (first, rest) = entries.split_at(entries.len() / 3);
let (second, third) = rest.split_at(entries.len() / 3);
async fn go(entries: &[DirEntry]) -> Vec<File> {
let mut files = Vec::with_capacity(entries.len());
for ent in entries {
let url = ent.url();
files.push(match ent.metadata().await {
Ok(cha) => File::from_follow(url, cha).await,
Err(_) => File::from_dummy(url, ent.file_type().await.ok()),
});
}
files
}
Ok(
futures::future::join_all([go(first), go(second), go(third)])
.await
.into_iter()
.flatten()
.collect(),
)
}
async fn assert_stale(dir: &UrlBuf, cha: Cha) -> Option<Cha> {
use std::io::ErrorKind;
match Cha::from_url(dir).await {
Ok(c) if !c.is_dir() => FilesOp::issue_error(dir, ErrorKind::NotADirectory).await,
Ok(c) if c.hits(cha) && PARTITIONS.read().heuristic(cha) => {}
Ok(c) => return Some(c),
Err(e) => FilesOp::issue_error(dir, e).await,
}
None
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/cha.rs | yazi-vfs/src/cha.rs | use std::io;
use yazi_fs::cha::{Cha, ChaKind};
use yazi_shared::url::AsUrl;
use crate::provider;
pub trait VfsCha: Sized {
fn from_url(url: impl AsUrl) -> impl Future<Output = io::Result<Self>>;
fn from_follow<U>(url: U, cha: Self) -> impl Future<Output = Self>
where
U: AsUrl;
}
impl VfsCha for Cha {
#[inline]
async fn from_url(url: impl AsUrl) -> io::Result<Self> {
let url = url.as_url();
Ok(Self::from_follow(url, provider::symlink_metadata(url).await?).await)
}
async fn from_follow<U>(url: U, mut cha: Self) -> Self
where
U: AsUrl,
{
let url = url.as_url();
let mut retain = cha.kind & (ChaKind::HIDDEN | ChaKind::SYSTEM);
if cha.is_link() {
retain |= ChaKind::FOLLOW;
cha = provider::metadata(url).await.unwrap_or(cha);
}
cha.attach(retain)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/fns.rs | yazi-vfs/src/fns.rs | use std::io::{self};
use yazi_macro::ok_or_not_found;
use yazi_shared::{strand::{StrandBuf, StrandLike}, url::{AsUrl, UrlBuf, UrlLike}};
use crate::provider;
#[inline]
pub async fn maybe_exists(url: impl AsUrl) -> bool {
match provider::symlink_metadata(url).await {
Ok(_) => true,
Err(e) => e.kind() != io::ErrorKind::NotFound,
}
}
// TODO: deprecate
pub async fn unique_name<F>(u: UrlBuf, append: F) -> io::Result<UrlBuf>
where
F: Future<Output = bool>,
{
match provider::symlink_metadata(&u).await {
Ok(_) => _unique_name(u, append.await).await,
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(u),
Err(e) => Err(e),
}
}
async fn _unique_name(mut url: UrlBuf, append: bool) -> io::Result<UrlBuf> {
let Some(stem) = url.stem().map(|s| s.to_owned()) else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty file stem"));
};
let dot_ext = match url.ext() {
Some(e) => {
let mut s = StrandBuf::with_capacity(url.kind(), e.len() + 1);
s.push_str(".");
s.try_push(e)?;
s
}
None => StrandBuf::default(),
};
let mut name = StrandBuf::with_capacity(url.kind(), stem.len() + dot_ext.len() + 5);
for i in 1u64.. {
name.clear();
name.try_push(&stem)?;
if append {
name.try_push(&dot_ext)?;
name.push_str(format!("_{i}"));
} else {
name.push_str(format!("_{i}"));
name.try_push(&dot_ext)?;
}
url.try_set_name(&name)?;
ok_or_not_found!(provider::symlink_metadata(&url).await, break);
}
Ok(url)
}
pub async fn unique_file(u: UrlBuf, is_dir: bool) -> io::Result<UrlBuf> {
let result = if is_dir {
provider::create_dir(&u).await
} else {
provider::create_new(&u).await.map(|_| ())
};
match result {
Ok(()) => Ok(u),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => _unique_file(u, is_dir).await,
Err(e) => Err(e),
}
}
async fn _unique_file(mut url: UrlBuf, is_dir: bool) -> io::Result<UrlBuf> {
let Some(stem) = url.stem().map(|s| s.to_owned()) else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty file stem"));
};
let dot_ext = match url.ext() {
Some(e) => {
let mut s = StrandBuf::with_capacity(url.kind(), e.len() + 1);
s.push_str(".");
s.try_push(e)?;
s
}
None => StrandBuf::default(),
};
let mut name = StrandBuf::with_capacity(url.kind(), stem.len() + dot_ext.len() + 5);
for i in 1u64.. {
name.clear();
name.try_push(&stem)?;
if is_dir {
name.try_push(&dot_ext)?;
name.push_str(format!("_{i}"));
} else {
name.push_str(format!("_{i}"));
name.try_push(&dot_ext)?;
}
url.try_set_name(&name)?;
let result = if is_dir {
provider::create_dir(&url).await
} else {
provider::create_new(&url).await.map(|_| ())
};
match result {
Ok(()) => break,
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => Err(e)?,
};
}
Ok(url)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/gate.rs | yazi-vfs/src/provider/gate.rs | use std::io;
use yazi_fs::provider::{Attrs, FileBuilder};
use yazi_shared::{scheme::SchemeKind, url::AsUrl};
#[derive(Clone, Copy, Default)]
pub struct Gate {
pub(super) append: bool,
pub(super) attrs: Attrs,
pub(super) create: bool,
pub(super) create_new: bool,
pub(super) read: bool,
pub(super) truncate: bool,
pub(super) write: bool,
}
impl FileBuilder for Gate {
type File = super::RwFile;
fn append(&mut self, append: bool) -> &mut Self {
self.append = append;
self
}
fn attrs(&mut self, attrs: Attrs) -> &mut Self {
self.attrs = attrs;
self
}
fn create(&mut self, create: bool) -> &mut Self {
self.create = create;
self
}
fn create_new(&mut self, create_new: bool) -> &mut Self {
self.create_new = create_new;
self
}
async fn open<U>(&self, url: U) -> io::Result<Self::File>
where
U: AsUrl,
{
let url = url.as_url();
Ok(match url.kind() {
SchemeKind::Regular | SchemeKind::Search => {
self.build::<yazi_fs::provider::local::Gate>().open(url).await?.into()
}
SchemeKind::Archive => {
Err(io::Error::new(io::ErrorKind::Unsupported, "Unsupported filesystem: archive"))?
}
SchemeKind::Sftp => self.build::<super::sftp::Gate>().open(url).await?.into(),
})
}
fn read(&mut self, read: bool) -> &mut Self {
self.read = read;
self
}
fn truncate(&mut self, truncate: bool) -> &mut Self {
self.truncate = truncate;
self
}
fn write(&mut self, write: bool) -> &mut Self {
self.write = write;
self
}
}
impl Gate {
fn build<T: FileBuilder>(self) -> T {
let mut gate = T::default();
if self.append {
gate.append(true);
}
gate.attrs(self.attrs);
if self.create {
gate.create(true);
}
if self.create_new {
gate.create_new(true);
}
if self.read {
gate.read(true);
}
if self.truncate {
gate.truncate(true);
}
if self.write {
gate.write(true);
}
gate
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/dir_entry.rs | yazi-vfs/src/provider/dir_entry.rs | use std::io;
use yazi_fs::{cha::{Cha, ChaType}, provider::FileHolder};
use yazi_shared::{path::PathBufDyn, strand::StrandCow, url::UrlBuf};
pub enum DirEntry {
Local(yazi_fs::provider::local::DirEntry),
Sftp(super::sftp::DirEntry),
}
impl FileHolder for DirEntry {
async fn file_type(&self) -> io::Result<ChaType> {
match self {
Self::Local(entry) => entry.file_type().await,
Self::Sftp(entry) => entry.file_type().await,
}
}
async fn metadata(&self) -> io::Result<Cha> {
match self {
Self::Local(entry) => entry.metadata().await,
Self::Sftp(entry) => entry.metadata().await,
}
}
fn name(&self) -> StrandCow<'_> {
match self {
Self::Local(entry) => entry.name(),
Self::Sftp(entry) => entry.name(),
}
}
fn path(&self) -> PathBufDyn {
match self {
Self::Local(entry) => entry.path(),
Self::Sftp(entry) => entry.path(),
}
}
fn url(&self) -> UrlBuf {
match self {
Self::Local(entry) => entry.url(),
Self::Sftp(entry) => entry.url(),
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/mod.rs | yazi-vfs/src/provider/mod.rs | yazi_macro::mod_pub!(sftp);
yazi_macro::mod_flat!(calculator copier dir_entry gate provider providers read_dir rw_file);
pub(super) fn init() { sftp::init(); }
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/copier.rs | yazi-vfs/src/provider/copier.rs | use std::{io::{self, SeekFrom}, sync::{Arc, atomic::{AtomicU64, Ordering}}};
use futures::{StreamExt, TryStreamExt};
use tokio::{io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, BufReader, BufWriter}, select, sync::{mpsc, oneshot}};
use yazi_fs::provider::{Attrs, FileBuilder};
use yazi_shared::url::{Url, UrlBuf};
use crate::provider::{self, Gate};
const BUF_SIZE: usize = 512 * 1024;
const PER_CHUNK: u64 = 8 * 1024 * 1024;
pub(super) async fn copy_impl(from: Url<'_>, to: Url<'_>, attrs: Attrs) -> io::Result<u64> {
let src = provider::open(from).await?;
let dist = provider::create(to).await?;
let mut reader = BufReader::with_capacity(BUF_SIZE, src);
let mut writer = BufWriter::with_capacity(BUF_SIZE, dist);
let written = tokio::io::copy(&mut reader, &mut writer).await?;
writer.flush().await?;
writer.get_ref().set_attrs(attrs).await.ok();
writer.shutdown().await.ok();
Ok(written)
}
pub(super) fn copy_with_progress_impl(
from: UrlBuf,
to: UrlBuf,
attrs: Attrs,
) -> mpsc::Receiver<io::Result<u64>> {
let acc = Arc::new(AtomicU64::new(0));
let (from, to) = (Arc::new(from), Arc::new(to));
let (prog_tx, prog_rx) = mpsc::channel(10);
let (done_tx, mut done_rx) = oneshot::channel();
let (acc_, prog_tx_) = (acc.clone(), prog_tx.clone());
tokio::spawn(async move {
let init = async {
let src = provider::open(&*from).await?;
let cha = src.metadata().await?;
let dist = provider::create(&*to).await?;
dist.set_len(cha.len).await?;
Ok((cha, Some(src), Some(dist)))
};
let (cha, mut src, mut dist) = match init.await {
Ok(r) => r,
Err(e) => {
prog_tx_.send(Err(e)).await.ok();
done_tx.send(()).ok();
return;
}
};
let chunks = cha.len.div_ceil(PER_CHUNK);
let it = futures::stream::iter(0..chunks)
.map(|i| {
let acc_ = acc_.clone();
let (from, to) = (from.clone(), to.clone());
let (src, dist) = (src.take(), dist.take());
async move {
let offset = i * PER_CHUNK;
let take = cha.len.saturating_sub(offset).min(PER_CHUNK);
let mut src = BufReader::with_capacity(BUF_SIZE, match src {
Some(f) => f,
None => provider::open(&*from).await?,
});
let mut dist = BufWriter::with_capacity(BUF_SIZE, match dist {
Some(f) => f,
None => Gate::default().write(true).open(&*to).await?,
});
src.seek(SeekFrom::Start(offset)).await?;
dist.seek(SeekFrom::Start(offset)).await?;
let mut src = src.take(take);
let mut buf = vec![0u8; 65536];
let mut copied = 0u64;
loop {
let n = src.read(&mut buf).await?;
if n == 0 {
break;
}
dist.write_all(&buf[..n]).await?;
copied += n as u64;
acc_.fetch_add(n as u64, Ordering::SeqCst);
}
dist.flush().await?;
if copied != take {
Err(io::Error::other(format!(
"short copy for chunk {i}: copied {copied} bytes, expected {take}"
)))
} else if i == chunks - 1 {
Ok(Some(dist.into_inner()))
} else {
dist.shutdown().await.ok();
Ok(None)
}
}
})
.buffer_unordered(4)
.try_fold(None, |first, file| async { Ok(first.or(file)) });
let mut result = select! {
r = it => r,
_ = prog_tx_.closed() => return,
};
done_tx.send(()).ok();
let n = acc_.swap(0, Ordering::SeqCst);
if n > 0 {
prog_tx_.send(Ok(n)).await.ok();
}
if let Ok(Some(file)) = &mut result {
file.set_attrs(attrs).await.ok();
file.shutdown().await.ok();
}
if let Err(e) = result {
prog_tx_.send(Err(e)).await.ok();
} else {
prog_tx_.send(Ok(0)).await.ok();
}
});
tokio::spawn(async move {
loop {
select! {
_ = &mut done_rx => break,
_ = prog_tx.closed() => break,
_ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {},
}
let n = acc.swap(0, Ordering::SeqCst);
if n > 0 {
prog_tx.send(Ok(n)).await.ok();
}
}
});
prog_rx
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/rw_file.rs | yazi-vfs/src/provider/rw_file.rs | use std::{io, pin::Pin};
use tokio::io::{AsyncRead, AsyncSeek, AsyncWrite};
use yazi_fs::provider::Attrs;
pub enum RwFile {
Tokio(tokio::fs::File),
Sftp(Box<yazi_sftp::fs::File>),
}
impl From<tokio::fs::File> for RwFile {
fn from(f: tokio::fs::File) -> Self { Self::Tokio(f) }
}
impl From<yazi_sftp::fs::File> for RwFile {
fn from(f: yazi_sftp::fs::File) -> Self { Self::Sftp(Box::new(f)) }
}
impl RwFile {
// FIXME: path
pub async fn metadata(&self) -> io::Result<yazi_fs::cha::Cha> {
Ok(match self {
Self::Tokio(f) => yazi_fs::cha::Cha::new("// FIXME", f.metadata().await?),
Self::Sftp(f) => super::sftp::Cha::try_from(("// FIXME".as_bytes(), &f.fstat().await?))?.0,
})
}
pub async fn set_attrs(&self, attrs: Attrs) -> io::Result<()> {
match self {
Self::Tokio(f) => {
let (perm, times) = (attrs.try_into(), attrs.try_into());
if perm.is_err() && times.is_err() {
return Ok(());
}
let std = f.try_clone().await?.into_std().await;
tokio::task::spawn_blocking(move || {
perm.map(|p| std.set_permissions(p)).ok();
times.map(|t| std.set_times(t)).ok();
})
.await?;
}
Self::Sftp(f) => {
if let Ok(attrs) = super::sftp::Attrs(attrs).try_into() {
f.fsetstat(&attrs).await?;
}
}
}
Ok(())
}
pub async fn set_len(&self, size: u64) -> io::Result<()> {
Ok(match self {
Self::Tokio(f) => f.set_len(size).await?,
Self::Sftp(f) => {
f.fsetstat(&yazi_sftp::fs::Attrs { size: Some(size), ..Default::default() }).await?
}
})
}
}
impl AsyncRead for RwFile {
#[inline]
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<io::Result<()>> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).poll_read(cx, buf),
Self::Sftp(f) => Pin::new(f).poll_read(cx, buf),
}
}
}
impl AsyncSeek for RwFile {
#[inline]
fn start_seek(mut self: Pin<&mut Self>, position: io::SeekFrom) -> io::Result<()> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).start_seek(position),
Self::Sftp(f) => Pin::new(f).start_seek(position),
}
}
#[inline]
fn poll_complete(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<io::Result<u64>> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).poll_complete(cx),
Self::Sftp(f) => Pin::new(f).poll_complete(cx),
}
}
}
impl AsyncWrite for RwFile {
#[inline]
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<Result<usize, io::Error>> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).poll_write(cx, buf),
Self::Sftp(f) => Pin::new(f).poll_write(cx, buf),
}
}
#[inline]
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), io::Error>> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).poll_flush(cx),
Self::Sftp(f) => Pin::new(f).poll_flush(cx),
}
}
#[inline]
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), io::Error>> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).poll_shutdown(cx),
Self::Sftp(f) => Pin::new(f).poll_shutdown(cx),
}
}
#[inline]
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> std::task::Poll<Result<usize, io::Error>> {
match &mut *self {
Self::Tokio(f) => Pin::new(f).poll_write_vectored(cx, bufs),
Self::Sftp(f) => Pin::new(f).poll_write_vectored(cx, bufs),
}
}
#[inline]
fn is_write_vectored(&self) -> bool {
match self {
Self::Tokio(f) => f.is_write_vectored(),
Self::Sftp(f) => f.is_write_vectored(),
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/read_dir.rs | yazi-vfs/src/provider/read_dir.rs | use std::io;
use yazi_fs::provider::DirReader;
pub enum ReadDir {
Local(yazi_fs::provider::local::ReadDir),
Sftp(super::sftp::ReadDir),
}
impl DirReader for ReadDir {
type Entry = super::DirEntry;
async fn next(&mut self) -> io::Result<Option<Self::Entry>> {
Ok(match self {
Self::Local(reader) => reader.next().await?.map(Self::Entry::Local),
Self::Sftp(reader) => reader.next().await?.map(Self::Entry::Sftp),
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/provider.rs | yazi-vfs/src/provider/provider.rs | use std::io;
use tokio::sync::mpsc;
use yazi_fs::{cha::Cha, provider::{Attrs, Capabilities, Provider, local::Local}};
use yazi_shared::{path::PathBufDyn, strand::AsStrand, url::{AsUrl, Url, UrlBuf, UrlCow}};
use super::{Providers, ReadDir, RwFile};
pub async fn absolute<'a, U>(url: &'a U) -> io::Result<UrlCow<'a>>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.absolute().await
}
pub async fn calculate<U>(url: U) -> io::Result<u64>
where
U: AsUrl,
{
let url = url.as_url();
if let Some(path) = url.as_local() {
yazi_fs::provider::local::SizeCalculator::total(path).await
} else {
super::SizeCalculator::total(url).await
}
}
pub async fn canonicalize<U>(url: U) -> io::Result<UrlBuf>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.canonicalize().await
}
pub async fn capabilities<U>(url: U) -> io::Result<Capabilities>
where
U: AsUrl,
{
Ok(Providers::new(url.as_url()).await?.capabilities())
}
pub async fn casefold<U>(url: U) -> io::Result<UrlBuf>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.casefold().await
}
pub async fn copy<U, V>(from: U, to: V, attrs: Attrs) -> io::Result<u64>
where
U: AsUrl,
V: AsUrl,
{
let (from, to) = (from.as_url(), to.as_url());
match (from.kind().is_local(), to.kind().is_local()) {
(true, true) => Local::new(from).await?.copy(to.loc(), attrs).await,
(false, false) if from.scheme().covariant(to.scheme()) => {
Providers::new(from).await?.copy(to.loc(), attrs).await
}
(true, false) | (false, true) | (false, false) => super::copy_impl(from, to, attrs).await,
}
}
pub async fn copy_with_progress<U, V, A>(
from: U,
to: V,
attrs: A,
) -> io::Result<mpsc::Receiver<Result<u64, io::Error>>>
where
U: AsUrl,
V: AsUrl,
A: Into<Attrs>,
{
let (from, to) = (from.as_url(), to.as_url());
match (from.kind().is_local(), to.kind().is_local()) {
(true, true) => Local::new(from).await?.copy_with_progress(to.loc(), attrs),
(false, false) if from.scheme().covariant(to.scheme()) => {
Providers::new(from).await?.copy_with_progress(to.loc(), attrs)
}
(true, false) | (false, true) | (false, false) => {
Ok(super::copy_with_progress_impl(from.to_owned(), to.to_owned(), attrs.into()))
}
}
}
pub async fn create<U>(url: U) -> io::Result<RwFile>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.create().await
}
pub async fn create_dir<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.create_dir().await
}
pub async fn create_dir_all<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.create_dir_all().await
}
pub async fn create_new<U>(url: U) -> io::Result<RwFile>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.create_new().await
}
pub async fn hard_link<U, V>(original: U, link: V) -> io::Result<()>
where
U: AsUrl,
V: AsUrl,
{
let (original, link) = (original.as_url(), link.as_url());
if original.scheme().covariant(link.scheme()) {
Providers::new(original).await?.hard_link(link.loc()).await
} else {
Err(io::Error::from(io::ErrorKind::CrossesDevices))
}
}
pub async fn identical<U, V>(a: U, b: V) -> io::Result<bool>
where
U: AsUrl,
V: AsUrl,
{
if let (Some(a), Some(b)) = (a.as_url().as_local(), b.as_url().as_local()) {
yazi_fs::provider::local::identical(a, b).await
} else {
Err(io::Error::new(io::ErrorKind::Unsupported, "Unsupported filesystem"))
}
}
pub async fn metadata<U>(url: U) -> io::Result<Cha>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.metadata().await
}
pub async fn must_identical<U, V>(a: U, b: V) -> bool
where
U: AsUrl,
V: AsUrl,
{
identical(a, b).await.unwrap_or(false)
}
pub async fn open<U>(url: U) -> io::Result<RwFile>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.open().await
}
pub async fn read_dir<U>(url: U) -> io::Result<ReadDir>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.read_dir().await
}
pub async fn read_link<U>(url: U) -> io::Result<PathBufDyn>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.read_link().await
}
pub async fn remove_dir<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.remove_dir().await
}
pub async fn remove_dir_all<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.remove_dir_all().await
}
pub async fn remove_dir_clean<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.remove_dir_clean().await
}
pub async fn remove_file<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.remove_file().await
}
pub async fn rename<U, V>(from: U, to: V) -> io::Result<()>
where
U: AsUrl,
V: AsUrl,
{
let (from, to) = (from.as_url(), to.as_url());
if from.scheme().covariant(to.scheme()) {
Providers::new(from).await?.rename(to.loc()).await
} else {
Err(io::Error::from(io::ErrorKind::CrossesDevices))
}
}
pub async fn symlink<U, S, F>(link: U, original: S, is_dir: F) -> io::Result<()>
where
U: AsUrl,
S: AsStrand,
F: AsyncFnOnce() -> io::Result<bool>,
{
Providers::new(link.as_url()).await?.symlink(original, is_dir).await
}
pub async fn symlink_dir<U, S>(link: U, original: S) -> io::Result<()>
where
U: AsUrl,
S: AsStrand,
{
Providers::new(link.as_url()).await?.symlink_dir(original).await
}
pub async fn symlink_file<U, S>(link: U, original: S) -> io::Result<()>
where
U: AsUrl,
S: AsStrand,
{
Providers::new(link.as_url()).await?.symlink_file(original).await
}
pub async fn symlink_metadata<U>(url: U) -> io::Result<Cha>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.symlink_metadata().await
}
pub async fn trash<U>(url: U) -> io::Result<()>
where
U: AsUrl,
{
Providers::new(url.as_url()).await?.trash().await
}
pub fn try_absolute<'a, U>(url: U) -> Option<UrlCow<'a>>
where
U: Into<UrlCow<'a>>,
{
let url = url.into();
match url.as_url() {
Url::Regular(_) | Url::Search { .. } => yazi_fs::provider::local::try_absolute(url),
Url::Archive { .. } => None, // TODO
Url::Sftp { .. } => crate::provider::sftp::try_absolute(url),
}
}
pub async fn write<U, C>(url: U, contents: C) -> io::Result<()>
where
U: AsUrl,
C: AsRef<[u8]>,
{
Providers::new(url.as_url()).await?.write(contents).await
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/providers.rs | yazi-vfs/src/provider/providers.rs | use std::io;
use tokio::sync::mpsc;
use yazi_fs::{cha::Cha, provider::{Attrs, Capabilities, Provider}};
use yazi_shared::{path::{AsPath, PathBufDyn}, strand::AsStrand, url::{Url, UrlBuf, UrlCow}};
#[derive(Clone)]
pub(super) enum Providers<'a> {
Local(yazi_fs::provider::local::Local<'a>),
Sftp(super::sftp::Sftp<'a>),
}
impl<'a> Provider for Providers<'a> {
type File = super::RwFile;
type Gate = super::Gate;
type Me<'b> = Providers<'b>;
type ReadDir = super::ReadDir;
type UrlCow = UrlCow<'a>;
async fn absolute(&self) -> io::Result<Self::UrlCow> {
match self {
Self::Local(p) => p.absolute().await,
Self::Sftp(p) => p.absolute().await,
}
}
async fn canonicalize(&self) -> io::Result<UrlBuf> {
match self {
Self::Local(p) => p.canonicalize().await,
Self::Sftp(p) => p.canonicalize().await,
}
}
fn capabilities(&self) -> Capabilities {
match self {
Self::Local(p) => p.capabilities(),
Self::Sftp(p) => p.capabilities(),
}
}
async fn casefold(&self) -> io::Result<UrlBuf> {
match self {
Self::Local(p) => p.casefold().await,
Self::Sftp(p) => p.casefold().await,
}
}
async fn copy<P>(&self, to: P, attrs: Attrs) -> io::Result<u64>
where
P: AsPath,
{
match self {
Self::Local(p) => p.copy(to, attrs).await,
Self::Sftp(p) => p.copy(to, attrs).await,
}
}
fn copy_with_progress<P, A>(&self, to: P, attrs: A) -> io::Result<mpsc::Receiver<io::Result<u64>>>
where
P: AsPath,
A: Into<Attrs>,
{
match self {
Self::Local(p) => p.copy_with_progress(to, attrs),
Self::Sftp(p) => p.copy_with_progress(to, attrs),
}
}
async fn create(&self) -> io::Result<Self::File> {
Ok(match self {
Self::Local(p) => p.create().await?.into(),
Self::Sftp(p) => p.create().await?.into(),
})
}
async fn create_dir(&self) -> io::Result<()> {
match self {
Self::Local(p) => p.create_dir().await,
Self::Sftp(p) => p.create_dir().await,
}
}
async fn create_dir_all(&self) -> io::Result<()> {
match self {
Self::Local(p) => p.create_dir_all().await,
Self::Sftp(p) => p.create_dir_all().await,
}
}
async fn create_new(&self) -> io::Result<Self::File> {
Ok(match self {
Self::Local(p) => p.create_new().await?.into(),
Self::Sftp(p) => p.create_new().await?.into(),
})
}
async fn hard_link<P>(&self, to: P) -> io::Result<()>
where
P: AsPath,
{
match self {
Self::Local(p) => p.hard_link(to).await,
Self::Sftp(p) => p.hard_link(to).await,
}
}
async fn metadata(&self) -> io::Result<Cha> {
match self {
Self::Local(p) => p.metadata().await,
Self::Sftp(p) => p.metadata().await,
}
}
async fn new<'b>(url: Url<'b>) -> io::Result<Self::Me<'b>> {
use yazi_shared::scheme::SchemeKind as K;
Ok(match url.kind() {
K::Regular | K::Search => Self::Me::Local(yazi_fs::provider::local::Local::new(url).await?),
K::Archive => {
Err(io::Error::new(io::ErrorKind::Unsupported, "Unsupported filesystem: archive"))?
}
K::Sftp => Self::Me::Sftp(super::sftp::Sftp::new(url).await?),
})
}
async fn open(&self) -> io::Result<Self::File> {
Ok(match self {
Self::Local(p) => p.open().await?.into(),
Self::Sftp(p) => p.open().await?.into(),
})
}
async fn read_dir(self) -> io::Result<Self::ReadDir> {
Ok(match self {
Self::Local(p) => Self::ReadDir::Local(p.read_dir().await?),
Self::Sftp(p) => Self::ReadDir::Sftp(p.read_dir().await?),
})
}
async fn read_link(&self) -> io::Result<PathBufDyn> {
match self {
Self::Local(p) => p.read_link().await,
Self::Sftp(p) => p.read_link().await,
}
}
async fn remove_dir(&self) -> io::Result<()> {
match self {
Self::Local(p) => p.remove_dir().await,
Self::Sftp(p) => p.remove_dir().await,
}
}
async fn remove_dir_all(&self) -> io::Result<()> {
match self {
Self::Local(p) => p.remove_dir_all().await,
Self::Sftp(p) => p.remove_dir_all().await,
}
}
async fn remove_file(&self) -> io::Result<()> {
match self {
Self::Local(p) => p.remove_file().await,
Self::Sftp(p) => p.remove_file().await,
}
}
async fn rename<P>(&self, to: P) -> io::Result<()>
where
P: AsPath,
{
match self {
Self::Local(p) => p.rename(to).await,
Self::Sftp(p) => p.rename(to).await,
}
}
async fn symlink<S, F>(&self, original: S, is_dir: F) -> io::Result<()>
where
S: AsStrand,
F: AsyncFnOnce() -> io::Result<bool>,
{
match self {
Self::Local(p) => p.symlink(original, is_dir).await,
Self::Sftp(p) => p.symlink(original, is_dir).await,
}
}
async fn symlink_dir<S>(&self, original: S) -> io::Result<()>
where
S: AsStrand,
{
match self {
Self::Local(p) => p.symlink_dir(original).await,
Self::Sftp(p) => p.symlink_dir(original).await,
}
}
async fn symlink_file<S>(&self, original: S) -> io::Result<()>
where
S: AsStrand,
{
match self {
Self::Local(p) => p.symlink_file(original).await,
Self::Sftp(p) => p.symlink_file(original).await,
}
}
async fn symlink_metadata(&self) -> io::Result<Cha> {
match self {
Self::Local(p) => p.symlink_metadata().await,
Self::Sftp(p) => p.symlink_metadata().await,
}
}
async fn trash(&self) -> io::Result<()> {
match self {
Self::Local(p) => p.trash().await,
Self::Sftp(p) => p.trash().await,
}
}
fn url(&self) -> Url<'_> {
match self {
Self::Local(p) => p.url(),
Self::Sftp(p) => p.url(),
}
}
async fn write<C>(&self, contents: C) -> io::Result<()>
where
C: AsRef<[u8]>,
{
match self {
Self::Local(p) => p.write(contents).await,
Self::Sftp(p) => p.write(contents).await,
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/calculator.rs | yazi-vfs/src/provider/calculator.rs | use std::{collections::VecDeque, io, time::{Duration, Instant}};
use yazi_fs::provider::{DirReader, FileHolder};
use yazi_shared::{Either, url::{AsUrl, UrlBuf}};
use super::ReadDir;
pub enum SizeCalculator {
File(Option<u64>),
Dir(VecDeque<Either<UrlBuf, ReadDir>>),
}
impl SizeCalculator {
pub async fn new<U>(url: U) -> io::Result<Self>
where
U: AsUrl,
{
let url = url.as_url();
let cha = super::symlink_metadata(url).await?;
Ok(if cha.is_dir() {
Self::Dir(VecDeque::from([Either::Left(url.to_owned())]))
} else {
Self::File(Some(cha.len))
})
}
pub async fn total<U>(url: U) -> io::Result<u64>
where
U: AsUrl,
{
let mut it = Self::new(url).await?;
let mut total = 0;
while let Some(n) = it.next().await? {
total += n;
}
Ok(total)
}
pub async fn next(&mut self) -> io::Result<Option<u64>> {
Ok(match self {
Self::File(size) => size.take(),
Self::Dir(buf) => Self::next_chunk(buf).await,
})
}
async fn next_chunk(buf: &mut VecDeque<Either<UrlBuf, ReadDir>>) -> Option<u64> {
let (mut i, mut size, now) = (0, 0, Instant::now());
macro_rules! pop_and_continue {
() => {{
buf.pop_front();
if buf.is_empty() {
return Some(size);
}
continue;
}};
}
while i < 2000 && now.elapsed() < Duration::from_millis(100) {
i += 1;
let front = buf.front_mut()?;
if let Either::Left(p) = front {
*front = match super::read_dir(p).await {
Ok(it) => Either::Right(it),
Err(_) => pop_and_continue!(),
};
}
let Ok(Some(ent)) = front.right_mut()?.next().await else {
pop_and_continue!();
};
let Ok(ft) = ent.file_type().await else { continue };
if ft.is_dir() {
buf.push_back(Either::Left(ent.url()));
} else if let Ok(cha) = ent.metadata().await {
size += cha.len;
}
}
Some(size)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/absolute.rs | yazi-vfs/src/provider/sftp/absolute.rs | use yazi_fs::CWD;
use yazi_shared::url::{UrlCow, UrlLike};
pub fn try_absolute<'a, U>(url: U) -> Option<UrlCow<'a>>
where
U: Into<UrlCow<'a>>,
{
try_absolute_impl(url.into())
}
fn try_absolute_impl<'a>(url: UrlCow<'a>) -> Option<UrlCow<'a>> {
if url.is_absolute() {
Some(url)
} else if let cwd = CWD.load()
&& cwd.scheme().covariant(url.scheme())
{
Some(cwd.try_join(url.loc()).ok()?.into())
} else {
None
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/gate.rs | yazi-vfs/src/provider/sftp/gate.rs | use std::io;
use yazi_config::vfs::{ServiceSftp, Vfs};
use yazi_fs::provider::{Attrs, FileBuilder};
use yazi_sftp::fs::Flags;
use yazi_shared::url::{AsUrl, Url};
use crate::provider::sftp::Conn;
#[derive(Clone, Copy, Default)]
pub struct Gate(crate::provider::Gate);
impl From<Gate> for Flags {
fn from(Gate(g): Gate) -> Self {
let mut flags = Self::empty();
if g.append {
flags |= Self::APPEND;
}
if g.create {
flags |= Self::CREATE;
}
if g.create_new {
flags |= Self::CREATE | Self::EXCLUDE;
}
if g.read {
flags |= Self::READ;
}
if g.truncate {
flags |= Self::TRUNCATE;
}
if g.write {
flags |= Self::WRITE;
}
flags
}
}
impl FileBuilder for Gate {
type File = yazi_sftp::fs::File;
fn append(&mut self, append: bool) -> &mut Self {
self.0.append(append);
self
}
fn attrs(&mut self, attrs: Attrs) -> &mut Self {
self.0.attrs(attrs);
self
}
fn create(&mut self, create: bool) -> &mut Self {
self.0.create(create);
self
}
fn create_new(&mut self, create_new: bool) -> &mut Self {
self.0.create_new(create_new);
self
}
async fn open<U>(&self, url: U) -> io::Result<Self::File>
where
U: AsUrl,
{
let url = url.as_url();
let (path, (name, config)) = match url {
Url::Sftp { loc, domain } => (*loc, Vfs::service::<&ServiceSftp>(domain).await?),
_ => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not an SFTP URL: {url:?}")))?,
};
let conn = Conn { name, config }.roll().await?;
let flags = Flags::from(*self);
let attrs = super::Attrs(self.0.attrs).try_into().unwrap_or_default();
let result = conn.open(path, flags, &attrs).await;
if self.0.create_new
&& let Err(yazi_sftp::Error::Status(status)) = &result
&& status.is_failure()
&& conn.lstat(path).await.is_ok()
{
return Err(io::Error::from(io::ErrorKind::AlreadyExists));
}
Ok(result?)
}
fn read(&mut self, read: bool) -> &mut Self {
self.0.read(read);
self
}
fn truncate(&mut self, truncate: bool) -> &mut Self {
self.0.truncate(truncate);
self
}
fn write(&mut self, write: bool) -> &mut Self {
self.0.write(write);
self
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/conn.rs | yazi-vfs/src/provider/sftp/conn.rs | use std::{io, sync::Arc, time::Duration};
use russh::keys::PrivateKeyWithHashAlg;
use yazi_config::vfs::ServiceSftp;
use yazi_fs::provider::local::Local;
#[derive(Clone, Copy)]
pub(super) struct Conn {
pub(super) name: &'static str,
pub(super) config: &'static ServiceSftp,
}
impl russh::client::Handler for Conn {
type Error = russh::Error;
async fn check_server_key(
&mut self,
_server_public_key: &russh::keys::PublicKey,
) -> Result<bool, Self::Error> {
Ok(true)
}
}
impl deadpool::managed::Manager for Conn {
type Error = io::Error;
type Type = yazi_sftp::Operator;
async fn create(&self) -> Result<Self::Type, Self::Error> {
let channel = self.connect().await.map_err(|e| {
io::Error::other(format!("Failed to connect to SFTP server `{}`: {e}", self.name))
})?;
let mut op = yazi_sftp::Operator::make(channel.into_stream());
op.init().await?;
Ok(op)
}
async fn recycle(
&self,
obj: &mut Self::Type,
_metrics: &deadpool::managed::Metrics,
) -> deadpool::managed::RecycleResult<Self::Error> {
if obj.is_closed() {
Err(deadpool::managed::RecycleError::Message("Channel closed".into()))
} else {
Ok(())
}
}
}
impl Conn {
pub(super) async fn roll(self) -> io::Result<deadpool::managed::Object<Self>> {
use deadpool::managed::PoolError;
let pool = *super::CONN.lock().entry(self.config).or_insert_with(|| {
Box::leak(Box::new(
deadpool::managed::Pool::builder(self)
.runtime(deadpool::Runtime::Tokio1)
.max_size(8)
.create_timeout(Some(Duration::from_secs(45)))
.build()
.unwrap(),
))
});
pool.get().await.map_err(|e| match e {
PoolError::Timeout(_) => io::Error::new(io::ErrorKind::TimedOut, e.to_string()),
PoolError::Backend(e) => e,
PoolError::Closed | PoolError::NoRuntimeSpecified | PoolError::PostCreateHook(_) => {
io::Error::other(e.to_string())
}
})
}
async fn connect(self) -> Result<russh::Channel<russh::client::Msg>, russh::Error> {
let pref = Arc::new(russh::client::Config {
inactivity_timeout: Some(std::time::Duration::from_secs(60)),
keepalive_interval: Some(std::time::Duration::from_secs(10)),
..Default::default()
});
let session = if self.config.password.is_some() {
self.connect_by_password(pref).await
} else if !self.config.key_file.as_os_str().is_empty() {
self.connect_by_key(pref).await
} else {
self.connect_by_agent(pref).await
}?;
let channel = session.channel_open_session().await?;
channel.request_subsystem(true, "sftp").await?;
Ok(channel)
}
async fn connect_by_password(
self,
pref: Arc<russh::client::Config>,
) -> Result<russh::client::Handle<Self>, russh::Error> {
let Some(password) = &self.config.password else {
return Err(russh::Error::InvalidConfig("Password not provided".to_owned()));
};
let mut session =
russh::client::connect(pref, (self.config.host.as_str(), self.config.port), self).await?;
if session.authenticate_password(&self.config.user, password).await?.success() {
Ok(session)
} else {
Err(russh::Error::InvalidConfig("Password authentication failed".to_owned()))
}
}
async fn connect_by_key(
self,
pref: Arc<russh::client::Config>,
) -> Result<russh::client::Handle<Self>, russh::Error> {
let key_file = &self.config.key_file;
if key_file.as_os_str().is_empty() {
return Err(russh::Error::InvalidConfig("Key file not provided".to_owned()));
};
let key = Local::regular(key_file)
.read_to_string()
.await
.map_err(|e| russh::Error::InvalidConfig(format!("Failed to read key file: {e}")))?;
let key = russh::keys::decode_secret_key(&key, self.config.key_passphrase.as_deref())?;
let mut session =
russh::client::connect(pref, (self.config.host.as_str(), self.config.port), self).await?;
let result = session
.authenticate_publickey(
&self.config.user,
PrivateKeyWithHashAlg::new(
Arc::new(key),
session.best_supported_rsa_hash().await?.flatten(),
),
)
.await?;
if result.success() {
Ok(session)
} else {
Err(russh::Error::InvalidConfig("Public key authentication failed".to_owned()))
}
}
async fn connect_by_agent(
self,
pref: Arc<russh::client::Config>,
) -> Result<russh::client::Handle<Self>, russh::Error> {
let identity_agent = &self.config.identity_agent;
if identity_agent.as_os_str().is_empty() {
return Err(russh::Error::InvalidConfig("Identity agent not provided".to_owned()));
};
#[cfg(unix)]
let mut agent = russh::keys::agent::client::AgentClient::connect_uds(identity_agent).await?;
#[cfg(windows)]
let mut agent =
russh::keys::agent::client::AgentClient::connect_named_pipe(identity_agent).await?;
let keys = agent.request_identities().await?;
if keys.is_empty() {
return Err(russh::Error::InvalidConfig("No keys found in SSH agent".to_owned()));
}
let mut session =
russh::client::connect(pref, (self.config.host.as_str(), self.config.port), self).await?;
for key in keys {
let hash_alg = session.best_supported_rsa_hash().await?.flatten();
match session.authenticate_publickey_with(&self.config.user, key, hash_alg, &mut agent).await
{
Ok(result) if result.success() => return Ok(session),
Ok(result) => tracing::debug!("Identity agent authentication failed: {result:?}"),
Err(e) => tracing::error!("Identity agent authentication error: {e}"),
}
}
Err(russh::Error::InvalidConfig("Public key authentication via agent failed".to_owned()))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/sftp.rs | yazi-vfs/src/provider/sftp/sftp.rs | use std::{io, sync::Arc};
use tokio::{io::{AsyncWriteExt, BufReader, BufWriter}, sync::mpsc::Receiver};
use yazi_config::vfs::{ServiceSftp, Vfs};
use yazi_fs::provider::{Capabilities, DirReader, FileHolder, Provider};
use yazi_sftp::fs::{Attrs, Flags};
use yazi_shared::{loc::LocBuf, path::{AsPath, PathBufDyn}, pool::InternStr, scheme::SchemeKind, strand::AsStrand, url::{Url, UrlBuf, UrlCow, UrlLike}};
use super::Cha;
use crate::provider::sftp::Conn;
#[derive(Clone)]
pub struct Sftp<'a> {
url: Url<'a>,
path: &'a typed_path::UnixPath,
name: &'static str,
config: &'static ServiceSftp,
}
impl<'a> Provider for Sftp<'a> {
type File = yazi_sftp::fs::File;
type Gate = super::Gate;
type Me<'b> = Sftp<'b>;
type ReadDir = super::ReadDir;
type UrlCow = UrlCow<'a>;
async fn absolute(&self) -> io::Result<Self::UrlCow> {
Ok(if let Some(u) = super::try_absolute(self.url) {
u
} else {
self.canonicalize().await?.into()
})
}
async fn canonicalize(&self) -> io::Result<UrlBuf> {
Ok(UrlBuf::Sftp {
loc: self.op().await?.realpath(self.path).await?.into(),
domain: self.name.intern(),
})
}
fn capabilities(&self) -> Capabilities { Capabilities { symlink: true } }
async fn casefold(&self) -> io::Result<UrlBuf> {
let Some((parent, name)) = self.url.parent().zip(self.url.name()) else {
return Ok(self.url.to_owned());
};
if !self.symlink_metadata().await?.is_link() {
return Ok(match self.canonicalize().await?.name() {
Some(name) => parent.try_join(name)?,
None => Err(io::Error::other("Cannot get filename"))?,
});
}
let mut it = Self::new(parent).await?.read_dir().await?;
let mut similar = None;
while let Some(entry) = it.next().await? {
let s = entry.name();
if !name.eq_ignore_ascii_case(&s) {
continue;
} else if s == name {
return Ok(entry.url());
} else if similar.is_none() {
similar = Some(s.into_owned());
} else {
return Err(io::Error::from(io::ErrorKind::NotFound));
}
}
similar
.map(|n| parent.try_join(n))
.transpose()?
.ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))
}
async fn copy<P>(&self, to: P, attrs: yazi_fs::provider::Attrs) -> io::Result<u64>
where
P: AsPath,
{
let to = to.as_path().as_unix()?;
let attrs = super::Attrs(attrs).try_into().unwrap_or_default();
let op = self.op().await?;
let from = op.open(self.path, Flags::READ, &Attrs::default()).await?;
let to = op.open(to, Flags::WRITE | Flags::CREATE | Flags::TRUNCATE, &attrs).await?;
let mut reader = BufReader::with_capacity(524288, from);
let mut writer = BufWriter::with_capacity(524288, to);
let written = tokio::io::copy(&mut reader, &mut writer).await?;
writer.flush().await?;
if !attrs.is_empty() {
writer.get_ref().fsetstat(&attrs).await.ok();
}
writer.shutdown().await.ok();
Ok(written)
}
fn copy_with_progress<P, A>(&self, to: P, attrs: A) -> io::Result<Receiver<io::Result<u64>>>
where
P: AsPath,
A: Into<yazi_fs::provider::Attrs>,
{
let to = UrlBuf::Sftp {
loc: LocBuf::<typed_path::UnixPathBuf>::saturated(
to.as_path().to_unix_owned()?,
SchemeKind::Sftp,
),
domain: self.name.intern(),
};
let from = self.url.to_owned();
Ok(crate::provider::copy_with_progress_impl(from, to, attrs.into()))
}
async fn create_dir(&self) -> io::Result<()> {
let op = self.op().await?;
let result = op.mkdir(self.path, Attrs::default()).await;
if let Err(yazi_sftp::Error::Status(status)) = &result
&& status.is_failure()
&& op.lstat(self.path).await.is_ok()
{
return Err(io::Error::from(io::ErrorKind::AlreadyExists));
}
Ok(result?)
}
async fn hard_link<P>(&self, to: P) -> io::Result<()>
where
P: AsPath,
{
let to = to.as_path().as_unix()?;
Ok(self.op().await?.hardlink(self.path, to).await?)
}
async fn metadata(&self) -> io::Result<yazi_fs::cha::Cha> {
let attrs = self.op().await?.stat(self.path).await?;
Ok(Cha::try_from((self.path.file_name().unwrap_or_default(), &attrs))?.0)
}
async fn new<'b>(url: Url<'b>) -> io::Result<Self::Me<'b>> {
match url {
Url::Regular(_) | Url::Search { .. } | Url::Archive { .. } => {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not a SFTP URL: {url:?}")))
}
Url::Sftp { loc, domain } => {
let (name, config) = Vfs::service::<&ServiceSftp>(domain).await?;
Ok(Self::Me { url, path: loc.as_inner(), name, config })
}
}
}
async fn read_dir(self) -> io::Result<Self::ReadDir> {
Ok(Self::ReadDir {
dir: Arc::new(self.url.to_owned()),
reader: self.op().await?.read_dir(self.path).await?,
})
}
async fn read_link(&self) -> io::Result<PathBufDyn> {
Ok(self.op().await?.readlink(self.path).await?.into())
}
async fn remove_dir(&self) -> io::Result<()> { Ok(self.op().await?.rmdir(self.path).await?) }
async fn remove_file(&self) -> io::Result<()> { Ok(self.op().await?.remove(self.path).await?) }
async fn rename<P>(&self, to: P) -> io::Result<()>
where
P: AsPath,
{
let to = to.as_path().as_unix()?;
let op = self.op().await?;
match op.rename_posix(self.path, &to).await {
Ok(()) => {}
Err(yazi_sftp::Error::Unsupported) => {
match op.remove(&to).await.map_err(io::Error::from) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => Err(e)?,
}
op.rename(self.path, &to).await?;
}
Err(e) => Err(e)?,
}
Ok(())
}
async fn symlink<S, F>(&self, original: S, _is_dir: F) -> io::Result<()>
where
S: AsStrand,
F: AsyncFnOnce() -> io::Result<bool>,
{
let original = original.as_strand().encoded_bytes();
Ok(self.op().await?.symlink(original, self.path).await?)
}
async fn symlink_metadata(&self) -> io::Result<yazi_fs::cha::Cha> {
let attrs = self.op().await?.lstat(self.path).await?;
Ok(Cha::try_from((self.path.file_name().unwrap_or_default(), &attrs))?.0)
}
async fn trash(&self) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "Trash not supported"))
}
#[inline]
fn url(&self) -> Url<'_> { self.url }
}
impl<'a> Sftp<'a> {
#[inline]
pub(super) async fn op(&self) -> io::Result<deadpool::managed::Object<Conn>> {
Conn { name: self.name, config: self.config }.roll().await
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/mod.rs | yazi-vfs/src/provider/sftp/mod.rs | yazi_macro::mod_flat!(absolute conn gate metadata read_dir sftp);
static CONN: yazi_shared::RoCell<
parking_lot::Mutex<
hashbrown::HashMap<
&'static yazi_config::vfs::ServiceSftp,
&'static deadpool::managed::Pool<Conn>,
>,
>,
> = yazi_shared::RoCell::new();
pub(super) fn init() { CONN.init(Default::default()); }
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/read_dir.rs | yazi-vfs/src/provider/sftp/read_dir.rs | use std::{io, sync::Arc};
use yazi_fs::provider::{DirReader, FileHolder};
use yazi_shared::{path::PathBufDyn, strand::StrandCow, url::{UrlBuf, UrlLike}};
use super::{Cha, ChaMode};
pub struct ReadDir {
pub(super) dir: Arc<UrlBuf>,
pub(super) reader: yazi_sftp::fs::ReadDir,
}
impl DirReader for ReadDir {
type Entry = DirEntry;
async fn next(&mut self) -> io::Result<Option<Self::Entry>> {
Ok(self.reader.next().await?.map(|entry| DirEntry { dir: self.dir.clone(), entry }))
}
}
// --- Entry
pub struct DirEntry {
dir: Arc<UrlBuf>,
entry: yazi_sftp::fs::DirEntry,
}
impl FileHolder for DirEntry {
async fn file_type(&self) -> io::Result<yazi_fs::cha::ChaType> {
Ok(ChaMode::try_from(self.entry.attrs())?.0.into())
}
async fn metadata(&self) -> io::Result<yazi_fs::cha::Cha> { Ok(Cha::try_from(&self.entry)?.0) }
fn name(&self) -> StrandCow<'_> { self.entry.name().into() }
fn path(&self) -> PathBufDyn { self.entry.path().into() }
fn url(&self) -> UrlBuf {
self.dir.try_join(self.entry.name()).expect("entry name is a valid component of the SFTP URL")
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-vfs/src/provider/sftp/metadata.rs | yazi-vfs/src/provider/sftp/metadata.rs | use std::{io, time::{Duration, UNIX_EPOCH}};
use yazi_fs::cha::ChaKind;
// --- Attrs
pub(crate) struct Attrs(pub(crate) yazi_fs::provider::Attrs);
impl TryFrom<Attrs> for yazi_sftp::fs::Attrs {
type Error = ();
fn try_from(value: Attrs) -> Result<Self, Self::Error> {
let attrs = Self {
size: None,
uid: None,
gid: None,
perm: value.0.mode.map(|m| m.bits() as u32),
atime: value.0.atime_dur().map(|d| d.as_secs() as u32),
mtime: value.0.mtime_dur().map(|d| d.as_secs() as u32),
extended: Default::default(),
};
if attrs.is_empty() { Err(()) } else { Ok(attrs) }
}
}
// --- Cha
pub(crate) struct Cha(pub(crate) yazi_fs::cha::Cha);
impl TryFrom<&yazi_sftp::fs::DirEntry> for Cha {
type Error = io::Error;
fn try_from(ent: &yazi_sftp::fs::DirEntry) -> Result<Self, Self::Error> {
let mut cha = Self::try_from((ent.name(), ent.attrs()))?;
cha.0.nlink = ent.nlink().unwrap_or_default();
Ok(cha)
}
}
impl TryFrom<(&[u8], &yazi_sftp::fs::Attrs)> for Cha {
type Error = io::Error;
fn try_from((name, attrs): (&[u8], &yazi_sftp::fs::Attrs)) -> Result<Self, Self::Error> {
let kind = if name.starts_with(b".") { ChaKind::HIDDEN } else { ChaKind::empty() };
Ok(Self(yazi_fs::cha::Cha {
kind,
mode: ChaMode::try_from(attrs)?.0,
len: attrs.size.unwrap_or(0),
atime: attrs.atime.and_then(|t| UNIX_EPOCH.checked_add(Duration::from_secs(t as u64))),
btime: None,
ctime: None,
mtime: attrs.mtime.and_then(|t| UNIX_EPOCH.checked_add(Duration::from_secs(t as u64))),
dev: 0,
uid: attrs.uid.unwrap_or(0),
gid: attrs.gid.unwrap_or(0),
nlink: 0,
}))
}
}
// --- ChaMode
pub(super) struct ChaMode(pub(super) yazi_fs::cha::ChaMode);
impl TryFrom<&yazi_sftp::fs::Attrs> for ChaMode {
type Error = io::Error;
fn try_from(attrs: &yazi_sftp::fs::Attrs) -> Result<Self, Self::Error> {
yazi_fs::cha::ChaMode::try_from(attrs.perm.unwrap_or_default() as u16)
.map(Self)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/lib.rs | yazi-parser/src/lib.rs | yazi_macro::mod_pub!(app cmp confirm help input mgr notify pick spot tasks which);
yazi_macro::mod_flat!(arrow step void);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/void.rs | yazi-parser/src/void.rs | use mlua::{FromLua, IntoLua, Lua, Value};
use yazi_shared::event::CmdCow;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct VoidOpt;
impl From<CmdCow> for VoidOpt {
fn from(_: CmdCow) -> Self { Self }
}
impl From<()> for VoidOpt {
fn from(_: ()) -> Self { Self }
}
impl FromLua for VoidOpt {
fn from_lua(_: Value, _: &Lua) -> mlua::Result<Self> { Ok(Self) }
}
impl IntoLua for VoidOpt {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua.create_table()?.into_lua(lua) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/arrow.rs | yazi-parser/src/arrow.rs | use anyhow::bail;
use mlua::{ExternalError, IntoLua, Lua, Value};
use yazi_shared::event::CmdCow;
use crate::Step;
#[derive(Clone, Copy, Debug, Default)]
pub struct ArrowOpt {
pub step: Step,
}
impl TryFrom<CmdCow> for ArrowOpt {
type Error = anyhow::Error;
fn try_from(c: CmdCow) -> Result<Self, Self::Error> {
let Ok(step) = c.first() else {
bail!("'step' is required for ArrowOpt");
};
Ok(Self { step })
}
}
impl From<isize> for ArrowOpt {
fn from(n: isize) -> Self { Self { step: n.into() } }
}
impl IntoLua for ArrowOpt {
fn into_lua(self, _: &Lua) -> mlua::Result<Value> { Err("unsupported".into_lua_err()) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/step.rs | yazi-parser/src/step.rs | use std::{num::ParseIntError, str::FromStr};
use yazi_shared::data::Data;
#[derive(Clone, Copy, Debug)]
pub enum Step {
Top,
Bot,
Prev,
Next,
Offset(isize),
Percent(i8),
}
impl Default for Step {
fn default() -> Self { Self::Offset(0) }
}
impl From<isize> for Step {
fn from(n: isize) -> Self { Self::Offset(n) }
}
impl FromStr for Step {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"top" => Self::Top,
"bot" => Self::Bot,
"prev" => Self::Prev,
"next" => Self::Next,
s if s.ends_with('%') => Self::Percent(s[..s.len() - 1].parse()?),
s => Self::Offset(s.parse()?),
})
}
}
impl TryFrom<&Data> for Step {
type Error = ParseIntError;
fn try_from(value: &Data) -> Result<Self, Self::Error> {
Ok(match value {
Data::Integer(i) => Self::from(*i as isize),
Data::String(s) => s.parse()?,
_ => "".parse()?,
})
}
}
impl Step {
pub fn add(self, pos: usize, len: usize, limit: usize) -> usize {
if len == 0 {
return 0;
}
let off = match self {
Self::Top => return 0,
Self::Bot => return len - 1,
Self::Prev => -1,
Self::Next => 1,
Self::Offset(n) => n,
Self::Percent(0) => 0,
Self::Percent(n) => n as isize * limit as isize / 100,
};
if matches!(self, Self::Prev | Self::Next) {
off.saturating_add_unsigned(pos).rem_euclid(len as _) as _
} else if off >= 0 {
pos.saturating_add_signed(off)
} else {
pos.saturating_sub(off.unsigned_abs())
}
.min(len - 1)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/tasks/update_succeed.rs | yazi-parser/src/tasks/update_succeed.rs | use anyhow::bail;
use mlua::{ExternalError, FromLua, IntoLua, Lua, Value};
use yazi_shared::{event::CmdCow, url::UrlBuf};
#[derive(Debug)]
pub struct UpdateSucceedOpt {
pub urls: Vec<UrlBuf>,
}
impl TryFrom<CmdCow> for UpdateSucceedOpt {
type Error = anyhow::Error;
fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
let Some(urls) = c.take_any("urls") else {
bail!("Invalid 'urls' argument in UpdateSucceedOpt");
};
Ok(Self { urls })
}
}
impl FromLua for UpdateSucceedOpt {
fn from_lua(_: Value, _: &Lua) -> mlua::Result<Self> { Err("unsupported".into_lua_err()) }
}
impl IntoLua for UpdateSucceedOpt {
fn into_lua(self, _: &Lua) -> mlua::Result<Value> { Err("unsupported".into_lua_err()) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/tasks/process_open.rs | yazi-parser/src/tasks/process_open.rs | use std::ffi::OsString;
use anyhow::anyhow;
use mlua::{ExternalError, FromLua, IntoLua, Lua, Value};
use yazi_shared::{CompletionToken, event::CmdCow, url::UrlCow};
// --- Exec
#[derive(Debug)]
pub struct ProcessOpenOpt {
pub cwd: UrlCow<'static>,
pub cmd: OsString,
pub args: Vec<UrlCow<'static>>,
pub block: bool,
pub orphan: bool,
pub done: Option<CompletionToken>,
pub spread: bool, // TODO: remove
}
impl TryFrom<CmdCow> for ProcessOpenOpt {
type Error = anyhow::Error;
fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
c.take_any("opt").ok_or_else(|| anyhow!("Missing 'opt' in ProcessOpenOpt"))
}
}
impl FromLua for ProcessOpenOpt {
fn from_lua(_: Value, _: &Lua) -> mlua::Result<Self> { Err("unsupported".into_lua_err()) }
}
impl IntoLua for ProcessOpenOpt {
fn into_lua(self, _: &Lua) -> mlua::Result<Value> { Err("unsupported".into_lua_err()) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/tasks/mod.rs | yazi-parser/src/tasks/mod.rs | yazi_macro::mod_flat!(process_open update_succeed);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/notify.rs | yazi-parser/src/app/notify.rs | use std::{str::FromStr, time::Duration};
use anyhow::anyhow;
use mlua::{ExternalError, ExternalResult};
use serde::Deserialize;
use yazi_config::{Style, THEME};
use yazi_shared::event::CmdCow;
pub struct NotifyOpt {
pub title: String,
pub content: String,
pub level: NotifyLevel,
pub timeout: Duration,
}
impl TryFrom<CmdCow> for NotifyOpt {
type Error = anyhow::Error;
fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
c.take_any("opt").ok_or_else(|| anyhow!("Invalid 'opt' in NotifyOpt"))
}
}
impl TryFrom<mlua::Table> for NotifyOpt {
type Error = mlua::Error;
fn try_from(t: mlua::Table) -> Result<Self, Self::Error> {
let timeout = t.raw_get("timeout")?;
if timeout < 0.0 {
return Err("timeout must be non-negative".into_lua_err());
}
let level = if let Ok(s) = t.raw_get::<mlua::String>("level") {
s.to_str()?.parse().into_lua_err()?
} else {
Default::default()
};
Ok(Self {
title: t.raw_get("title")?,
content: t.raw_get("content")?,
level,
timeout: Duration::from_secs_f64(timeout),
})
}
}
// --- Level
#[derive(Clone, Copy, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum NotifyLevel {
#[default]
Info,
Warn,
Error,
}
impl NotifyLevel {
pub fn icon(self) -> &'static str {
match self {
Self::Info => &THEME.notify.icon_info,
Self::Warn => &THEME.notify.icon_warn,
Self::Error => &THEME.notify.icon_error,
}
}
pub fn style(self) -> Style {
match self {
Self::Info => THEME.notify.title_info,
Self::Warn => THEME.notify.title_warn,
Self::Error => THEME.notify.title_error,
}
}
}
impl FromStr for NotifyLevel {
type Err = serde::de::value::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::deserialize(serde::de::value::StrDeserializer::new(s))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/update_progress.rs | yazi-parser/src/app/update_progress.rs | use anyhow::bail;
use ordered_float::OrderedFloat;
use serde::Serialize;
use yazi_shared::event::CmdCow;
pub struct UpdateProgressOpt {
pub summary: TaskSummary,
}
impl TryFrom<CmdCow> for UpdateProgressOpt {
type Error = anyhow::Error;
fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
let Some(summary) = c.take_any("summary") else {
bail!("Invalid 'summary' in UpdateProgressOpt");
};
Ok(Self { summary })
}
}
// --- Progress
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
pub struct TaskSummary {
pub total: u32,
pub success: u32,
pub failed: u32,
pub percent: Option<OrderedFloat<f32>>,
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/mouse.rs | yazi-parser/src/app/mouse.rs | use crossterm::event::MouseEvent;
pub struct MouseOpt {
pub event: MouseEvent,
}
impl From<MouseEvent> for MouseOpt {
fn from(event: MouseEvent) -> Self { Self { event } }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/deprecate.rs | yazi-parser/src/app/deprecate.rs | use anyhow::bail;
use yazi_shared::{SStr, event::CmdCow};
pub struct DeprecateOpt {
pub content: SStr,
}
impl TryFrom<CmdCow> for DeprecateOpt {
type Error = anyhow::Error;
fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
let Ok(content) = c.take("content") else {
bail!("Invalid 'content' in DeprecateOpt");
};
Ok(Self { content })
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/mod.rs | yazi-parser/src/app/mod.rs | yazi_macro::mod_flat!(deprecate mouse notify plugin resume stop update_progress);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/resume.rs | yazi-parser/src/app/resume.rs | use tokio::sync::oneshot;
use yazi_shared::event::CmdCow;
pub struct ResumeOpt {
pub tx: Option<oneshot::Sender<()>>,
}
impl From<CmdCow> for ResumeOpt {
fn from(mut c: CmdCow) -> Self { Self { tx: c.take_any("tx") } }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/stop.rs | yazi-parser/src/app/stop.rs | use tokio::sync::oneshot;
use yazi_shared::event::CmdCow;
pub struct StopOpt {
pub tx: Option<oneshot::Sender<()>>,
}
impl From<CmdCow> for StopOpt {
fn from(mut c: CmdCow) -> Self { Self { tx: c.take_any("tx") } }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-parser/src/app/plugin.rs | yazi-parser/src/app/plugin.rs | use std::{borrow::Cow, fmt::Debug, str::FromStr};
use anyhow::bail;
use hashbrown::HashMap;
use mlua::{Lua, Table};
use serde::Deserialize;
use yazi_shared::{SStr, data::{Data, DataKey}, event::{Cmd, CmdCow}};
pub type PluginCallback = Box<dyn FnOnce(&Lua, Table) -> mlua::Result<()> + Send + Sync>;
#[derive(Default)]
pub struct PluginOpt {
pub id: SStr,
pub args: HashMap<DataKey, Data>,
pub mode: PluginMode,
pub cb: Option<PluginCallback>,
}
impl TryFrom<CmdCow> for PluginOpt {
type Error = anyhow::Error;
fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
if let Some(opt) = c.take_any("opt") {
return Ok(opt);
}
let Some(id) = c.take_first::<SStr>().ok().filter(|s| !s.is_empty()) else {
bail!("plugin id cannot be empty");
};
let args = if let Ok(s) = c.second() {
let (words, last) = yazi_shared::shell::unix::split(s, true)?;
Cmd::parse_args(words, last)?
} else {
Default::default()
};
let mode = c.str("mode").parse().unwrap_or_default();
Ok(Self { id: Self::normalize_id(id), args, mode, cb: c.take_any("callback") })
}
}
impl Debug for PluginOpt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PluginOpt")
.field("id", &self.id)
.field("args", &self.args)
.field("mode", &self.mode)
.field("cb", &self.cb.is_some())
.finish()
}
}
impl PluginOpt {
pub fn new_callback(id: impl Into<SStr>, cb: PluginCallback) -> Self {
Self {
id: Self::normalize_id(id.into()),
mode: PluginMode::Sync,
cb: Some(cb),
..Default::default()
}
}
fn normalize_id(s: SStr) -> SStr {
match s {
Cow::Borrowed(s) => s.trim_end_matches(".main").into(),
Cow::Owned(mut s) => {
s.truncate(s.trim_end_matches(".main").len());
s.into()
}
}
}
}
// --- Mode
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum PluginMode {
#[default]
Auto,
Sync,
Async,
}
impl FromStr for PluginMode {
type Err = serde::de::value::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::deserialize(serde::de::value::StrDeserializer::new(s))
}
}
impl PluginMode {
pub fn auto_then(self, sync: bool) -> Self {
if self != Self::Auto {
return self;
}
if sync { Self::Sync } else { Self::Async }
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.