initial dotfiles

This commit is contained in:
srtk 2026-04-25 16:39:11 +05:30
commit 45e5fe53d2
370 changed files with 25449 additions and 0 deletions

View file

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright © 2024
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,29 @@
# audio-preview.yazi
A plugin for [yazi](https://github.com/sxyazi/yazi) to preview soundfiles as spectrogram
using sox
## Requirements
- `sox`
## Installation
```sh
ya pack -a 'gesellkammer/audio-preview'
```
## Usage
Add this to your `yazi.toml`:
```toml
[plugin]
prepend_previewers = [
{ mime = "audio/*", run = "audio-preview" },
]
prepend_preloaders = [
{ mime = "audio/*", run = "audio-preview" },
]
```

View file

@ -0,0 +1,63 @@
local M = {}
function M:peek(job)
local start, cache = os.clock(), ya.file_cache(job)
if not cache or self:preload() ~= 1 then
return
end
ya.sleep(math.max(0, 0.1 + start - os.clock()))
ya.image_show(cache, job.area)
ya.preview_widgets(job, {})
end
function M:seek(job, units)
local h = cx.active.current.hovered
if h and h.url == job.file.url then
local step = ya.clamp(-1, units, 1)
ya.manager_emit("peek", { math.max(0, cx.active.preview.skip + step), only_if = job.file.url })
end
end
function M:preload(job)
ya.dbg("Preloading audio-preview ***")
if not job then
return 1
end
local percentage = 5 + job.skip
if percentage > 95 then
ya.manager_emit("peek", { 90, only_if = job.file.url, upper_bound = true })
return 2
end
local cache = ya.file_cache(job)
if not cache then
return 1
end
local cha = fs.cha(cache)
if cha and cha.len > 0 then
return 1
end
-- generate image
ya.err("Calling sox for: " .. tostring(job.file.url) .. ", cache: " .. tostring(cache))
local child, code = Command("sox")
:arg({tostring(job.file.url),
"-n", "trim", "0:00", "1:00",
"remix", "1",
"rate", "12k",
"spectrogram",
"-o", tostring(cache)})
:spawn()
if not child then
ya.err("spawn `sox` command returns " .. tostring(code))
return 0
end
local status = child:wait()
return status and status.success and 1 or 2
end
return M

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 walldmtd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,42 @@
# blender-preview.yazi
A [Yazi](https://github.com/sxyazi/yazi) plugin to preview Blender's .blend and
.blend1 files.
> [!TIP]
> Blender's thumbnails are limited to 128x128 pixels.
> [zoom.yazi](https://github.com/yazi-rs/plugins/tree/main/zoom.yazi) can help
increase the size, but won't change the resolution.
## Requirements
`blender-thumbnailer` needs to be available on the path
(usually done automatically when Blender is installed).
## Installation
```sh
ya pkg add walldmtd/blender-preview
```
## Usage
Add this to `yazi.toml`:
```toml
[plugin]
prepend_preloaders = [
{ name = "*.blend", run = "blender-preview" },
{ name = "*.blend1", run = "blender-preview" },
]
prepend_previewers = [
{ name = "*.blend", run = "blender-preview" },
{ name = "*.blend1", run = "blender-preview" },
]
```
## Acknowledgements
- [Yazi](https://github.com/sxyazi/yazi), for
[magick.lua](https://github.com/sxyazi/yazi/blob/main/yazi-plugin/preset/plugins/magick.lua)
(used as a base for this plugin)

View file

@ -0,0 +1,44 @@
local M = {}
function M:peek(job)
local start, cache = os.clock(), ya.file_cache(job)
if not cache then
return
end
local ok, err = self:preload(job)
if not ok or err then
return ya.preview_widget(job, err)
end
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err)
end
function M:seek() end
function M:preload(job)
local cache = ya.file_cache(job)
if not cache or fs.cha(cache) then
return true
end
local cmd = Command("blender-thumbnailer"):arg({ tostring(job.file.url), tostring(cache) })
local status, err = cmd:status()
if not status then
return true, Err("Failed to start `blender-thumbnailer`, error: %s", err)
elseif not status.success then
return false, Err("`blender-thumbnailer` exited with error code: %s", status.code)
else
return true
end
end
function M:spot(job)
require("file"):spot(job)
end
return M

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Ciarán O'Brien
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,173 @@
<h1 align="center">🗜️ compress.yazi</h1>
<p align="center">
<b>A blazing fast, flexible archive plugin for <a href="https://github.com/sxyazi/yazi">Yazi</a></b><br>
<i>Effortlessly compress your files and folders with style!</i>
</p>
---
## 📖 Table of Contents
- [Features](#-features)
- [Supported File Types](#-supported-file-types)
- [Installation](#%EF%B8%8F-installation)
- [Keymap Example](#-keymap-example)
- [Usage](#%EF%B8%8F-usage)
- [Flags](#%EF%B8%8F-flags)
- [Tips](#-tips)
- [Credits](#-credits)
---
## 🚀 Features
- 🗂️ **Multi-format support:** zip, 7z, rar, tar, tar.gz, tar.xz, tar.bz2, tar.zst, tar.lz4, tar.lha
- 🌍 **Cross-platform:** Works on Unix & Windows
- 🔒 **Password protection:** Secure your archives (zip/7z/rar)
- 🛡️ **Header encryption:** Hide file lists (7z/rar)
- ⚡ **Compression level:** Choose your balance of speed vs. size
- 🛑 **Overwrite safety:** Never lose files by accident
- 🎯 **Seamless Yazi integration:** Fast, native-like UX
---
## 📦 Supported File Types
| Extension | Default Command | 7z Command | Bsdtar Command (Win10+ & Unix) |
| ------------- | ----------------- | -------------- | ------------------------------ |
| `.zip` | `zip -r` | `7z a -tzip` | `tar -caf` |
| `.7z` | `7z a` | `7z a` | |
| `.rar` | `rar a` | | |
| `.tar` | `tar rpf` | | `tar rpf` |
| `.tar.gz` | `tar rpf + gzip` | `7z a -tgzip` | `tar -czf` |
| `.tar.xz` | `tar rpf + xz` | `7z a -txz` | `tar -cJf` |
| `.tar.bz2` | `tar rpf + bzip2` | `7z a -tbzip2` | `tar -cjf` |
| `.tar.zst` | `tar rpf + zstd` | | `tar --zstd -cf` |
| `.tar.lz4` | `tar rpf + lz4` | | |
| `.tar.lha` | `tar rpf + lha` | | |
---
## ⚡️ Installation
```bash
# Unix
git clone https://github.com/KKV9/compress.yazi.git ~/.config/yazi/plugins/compress.yazi
# Windows (CMD, not PowerShell!)
git clone https://github.com/KKV9/compress.yazi.git %AppData%\yazi\config\plugins\compress.yazi
# Or with yazi plugin manager
ya pkg add KKV9/compress
```
---
### 🔧 Extras (Windows)
To enable additional compression formats and features on Windows, follow these steps:
1. **Install [7-Zip](https://www.7-zip.org/):**
Add `C:\Program Files\7-Zip` to your `PATH`.
This enables support for `.7z` archives and password-protected `.zip` files.
2. **Alternative: Install [Nanazip](https://github.com/M2Team/NanaZip):**
A modern alternative to 7-Zip with similar functionality and extra features.
3. **Install [WinRAR](https://www.win-rar.com/download.html):**
Add `C:\Program Files\WinRAR` to your `PATH`.
This enables support for `.rar` archives.
4. **Install Additional Tools:**
To use formats like `lha`, `lz4`, `gzip`, etc., install their respective tools and ensure they are added to your `PATH`.
---
## 🎹 Keymap Example
Add this to your `keymap.toml`:
```toml
[[mgr.prepend_keymap]]
on = [ "c", "a", "a" ]
run = "plugin compress"
desc = "Archive selected files"
[[mgr.prepend_keymap]]
on = [ "c", "a", "p" ]
run = "plugin compress -p"
desc = "Archive selected files (password)"
[[mgr.prepend_keymap]]
on = [ "c", "a", "h" ]
run = "plugin compress -ph"
desc = "Archive selected files (password+header)"
[[mgr.prepend_keymap]]
on = [ "c", "a", "l" ]
run = "plugin compress -l"
desc = "Archive selected files (compression level)"
[[mgr.prepend_keymap]]
on = [ "c", "a", "u" ]
run = "plugin compress -phl"
desc = "Archive selected files (password+header+level)"
```
---
## 🛠️ Usage
1. **Select files/folders** in Yazi.
2. Press <kbd>c</kbd> <kbd>a</kbd> to open the archive dialog.
3. Choose:
- <kbd>a</kbd> for a standard archive
- <kbd>p</kbd> for password protection (zip/7z/rar)
- <kbd>h</kbd> to encrypt header (7z/rar)
- <kbd>l</kbd> to set compression level (all compression algorithims)
- <kbd>u</kbd> for all options together
4. **Type a name** for your archive (or leave blank for suggested name).
5. **Enter password** and/or **compression level** if prompted.
6. **Overwrite protect** if a file already exists, the new file will be given a suffix _#.
7. Enjoy your shiny new archive!
---
## 🏳️‍🌈 Flags
- Combine flags for more power!
- when separating flags with spaces, make sure to single quote them (eg., `'-ph rar'`)
- `-p` Password protect (zip/7z/rar)
- `-h` Encrypt header (7z/rar)
- `-l` Set compression level (all compression algorithims)
- `<extention>` Specify a default extention (eg., `7z`, `tar.gz`)
#### Combining multiple flags:
```toml
[[mgr.prepend_keymap]]
on = [ "c", "a", "7" ]
run = "plugin compress '-ph 7z'"
desc = "Archive selected files to 7z (password+header)"
[[mgr.prepend_keymap]]
on = [ "c", "a", "r" ]
run = "plugin compress '-p -l rar'"
desc = "Archive selected files to rar (password+level)"
```
---
## 💡 Tips
- The file extension **must** match a supported type.
- The required compression tool **must** be installed and in your `PATH` (7zip/rar etc.).
- If no extention is provided, the default extention (zip) will be appended automatically.
---
## 📣 Credits
Made with ❤️ for [Yazi](https://github.com/sxyazi/yazi) by [KKV9](https://github.com/KKV9).
Contributions are welcome! Feel free to submit a pull request.
---

View file

@ -0,0 +1,497 @@
-- Check for windows
local is_windows = ya.target_family() == "windows"
-- Define flags and strings
local is_password, is_encrypted, is_level, cmd_password, cmd_level, default_extension = false, false, false, "", "", "zip"
-- Function to check valid filename
local function is_valid_filename(name)
-- Trim whitespace from both ends
name = name:match("^%s*(.-)%s*$")
if name == "" then
return false
end
if is_windows then
-- Windows forbidden chars and reserved names
if name:find('[<>:"/\\|%?%*]') then
return false
end
else
-- Unix forbidden chars
if name:find("/") or name:find("%z") then
return false
end
end
return true
end
-- Function to send notifications
local function notify_error(message, urgency)
ya.notify(
{
title = "Archive",
content = message,
level = urgency,
timeout = 5
}
)
end
-- Function to check if command is available
local function is_command_available(cmd)
local stat_cmd
if is_windows then
stat_cmd = string.format("where %s > nul 2>&1", cmd)
else
stat_cmd = string.format("command -v %s >/dev/null 2>&1", cmd)
end
local cmd_exists = os.execute(stat_cmd)
if cmd_exists then
return true
else
return false
end
end
-- Function to change command arrays --> string -- Use first command available or first command
local function find_command_name(cmd_list)
for _, cmd in ipairs(cmd_list) do
if is_command_available(cmd) then
return cmd
end
end
return cmd_list[1] -- Return first command as fallback
end
-- Function to append filename to it's parent directory url
local function combine_url(path, file)
path, file = Url(path), Url(file)
return tostring(path:join(file))
end
-- Function to make a table of selected or hovered files: path = filenames
local selected_or_hovered =
ya.sync(
function()
local tab, paths, names, path_fnames = cx.active, {}, {}, {}
for _, u in pairs(tab.selected) do
paths[#paths + 1] = tostring(u.parent)
names[#names + 1] = tostring(u.name)
end
if #paths == 0 and tab.current.hovered then
paths[1] = tostring(tab.current.hovered.url.parent)
names[1] = tostring(tab.current.hovered.name)
end
for idx, name in ipairs(names) do
if not path_fnames[paths[idx]] then
path_fnames[paths[idx]] = {}
end
table.insert(path_fnames[paths[idx]], name)
end
return path_fnames, names, tostring(tab.current.cwd)
end
)
-- Table of archive commands
local archive_commands = {
["%.zip$"] = {
{command = "zip", args = {"-r"}, level_arg = "-", level_min = 0, level_max = 9, passwordable = true},
{
command = {"7z", "7zz", "7za"},
args = {"a", "-tzip"},
level_arg = "-mx=",
level_min = 0,
level_max = 9,
passwordable = true
},
{
command = {"tar", "bsdtar"},
args = {"-caf"},
level_arg = {"--option", "compression-level="},
level_min = 1,
level_max = 9
}
},
["%.7z$"] = {
{
command = {"7z", "7zz", "7za"},
args = {"a"},
level_arg = "-mx=",
level_min = 0,
level_max = 9,
header_arg = "-mhe=on",
passwordable = true
}
},
["%.rar$"] = {
{
command = "rar",
args = {"a"},
level_arg = "-m",
level_min = 0,
level_max = 5,
header_arg = "-hp",
passwordable = true
}
},
["%.tar.gz$"] = {
{command = {"tar", "bsdtar"}, args = {"rpf"}, level_arg = "-", level_min = 1, level_max = 9, compress = "gzip"},
{
command = {"tar", "bsdtar"},
args = {"rpf"},
level_arg = "-mx=",
level_min = 1,
level_max = 9,
compress = "7z",
compress_args = {"a", "-tgzip"}
},
{
command = {"tar", "bsdtar"},
args = {"-czf"},
level_arg = {"--option", "gzip:compression-level="},
level_min = 1,
level_max = 9
}
},
["%.tar.xz$"] = {
{command = {"tar", "bsdtar"}, args = {"rpf"}, level_arg = "-", level_min = 1, level_max = 9, compress = "xz"},
{
command = {"tar", "bsdtar"},
args = {"rpf"},
level_arg = "-mx=",
level_min = 1,
level_max = 9,
compress = "7z",
compress_args = {"a", "-txz"}
},
{
command = {"tar", "bsdtar"},
args = {"-cJf"},
level_arg = {"--option", "xz:compression-level="},
level_min = 1,
level_max = 9
}
},
["%.tar.bz2$"] = {
{command = {"tar", "bsdtar"}, args = {"rpf"}, level_arg = "-", level_min = 1, level_max = 9, compress = "bzip2"},
{
command = {"tar", "bsdtar"},
args = {"rpf"},
level_arg = "-mx=",
level_min = 1,
level_max = 9,
compress = "7z",
compress_args = {"a", "-tbzip2"}
},
{
command = {"tar", "bsdtar"},
args = {"-cjf"},
level_arg = {"--option", "bzip2:compression-level="},
level_min = 1,
level_max = 9
}
},
["%.tar.zst$"] = {
{
command = {"tar", "bsdtar"},
args = {"rpf"},
level_arg = "-",
level_min = 1,
level_max = 22,
compress = "zstd",
compress_args = {"--ultra"}
}
},
["%.tar.lz4$"] = {
{
command = {"tar", "bsdtar"},
args = {"rpf"},
level_arg = "-",
level_min = 1,
level_max = 12,
compress = "lz4"
}
},
["%.tar.lha$"] = {
{
command = {"tar", "bsdtar"},
args = {"rpf"},
level_arg = "-o",
level_min = 5,
level_max = 7,
compress = "lha",
compress_args = {"-a"}
}
},
["%.tar$"] = {
{command = {"tar", "bsdtar"}, args = {"rpf"}}
}
}
return {
entry = function(_, job)
-- Parse flags and default extension
if job.args ~= nil then
for _, arg in ipairs(job.args) do
if arg:match("^%-(%w+)$") then
-- Handle combined flags (e.g., -phl)
for flag in arg:sub(2):gmatch(".") do
if flag == "p" then
is_password = true
elseif flag == "h" then
is_encrypted = true
elseif flag == "l" then
is_level = true
end
end
elseif arg:match("^[%w%.]+$") then
-- Handle default extension (e.g., 7z, zip)
if archive_commands["%." .. arg .. "$"] then
default_extension = arg
else
notify_error(string.format("Unsupported extension: %s", arg), "warn")
end
else
notify_error(string.format("Unknown argument: %s", arg), "warn")
end
end
end
-- Exit visual mode
ya.emit("escape", {visual = true})
-- Define file table and output_dir (pwd)
local path_fnames, fnames, output_dir = selected_or_hovered()
-- Get archive filename
local output_name, event =
ya.input(
{
title = "Create archive:",
pos = {"top-center", y = 3, w = 40}
}
)
if event ~= 1 then
return
end
-- Determine the default name for the archive
local default_name = #fnames == 1 and fnames[1] or Url(output_dir).name
output_name = output_name == "" and string.format("%s.%s", default_name, default_extension) or output_name
-- Add default extension if none is specified
if not output_name:match("%.%w+$") then
output_name = string.format("%s.%s", output_name, default_extension)
end
-- Validate the final archive filename
if not is_valid_filename(output_name) then
notify_error("Invalid archive filename", "error")
return
end
-- Match user input to archive command
local archive_cmd,
archive_args,
archive_compress,
archive_level_arg,
archive_level_min,
archive_level_max,
archive_header_arg,
archive_passwordable,
archive_compress_args
local matched_pattern = false
for pattern, cmd_list in pairs(archive_commands) do
if output_name:match(pattern) then
matched_pattern = true -- Mark that file extension is correct
for _, cmd in ipairs(cmd_list) do
-- Check if archive_cmd is available
local find_command = type(cmd.command) == "table" and find_command_name(cmd.command) or cmd.command
if is_command_available(find_command) then
-- Check if compress_cmd (if listed) is available
if cmd.compress == nil or is_command_available(cmd.compress) then
archive_cmd = find_command
archive_args = cmd.args
archive_compress = cmd.compress or ""
archive_level_arg = is_level and cmd.level_arg or ""
archive_level_min = cmd.level_min
archive_level_max = cmd.level_max
archive_header_arg = is_encrypted and cmd.header_arg or ""
archive_passwordable = cmd.passwordable or false
archive_compress_args = cmd.compress_args or {}
break
end
end
end
if archive_cmd then
break
end
end
end
-- Check if no archive command is available for the extension
if not matched_pattern then
notify_error("Unsupported file extension", "error")
return
end
-- Check if no suitable archive program was found
if not archive_cmd then
notify_error("Could not find a suitable archive program for the selected file extension", "error")
return
end
-- Check if archive command has multiple names
if type(archive_cmd) == "table" then
archive_cmd = find_command_name(archive_cmd)
end
-- Exit if archive command is not available
if not is_command_available(archive_cmd) then
notify_error(string.format("%s not available", archive_cmd), "error")
return
end
-- Exit if compress command is not available
if archive_compress ~= "" and not is_command_available(archive_compress) then
notify_error(string.format("%s compression not available", archive_compress), "error")
return
end
-- Add password arg if selected
if archive_passwordable and is_password then
local output_password, event =
ya.input(
{
title = "Enter password:",
obscure = true,
pos = {"top-center", y = 3, w = 40}
}
)
if event ~= 1 then
return
end
if output_password ~= "" then
cmd_password = "-P" .. output_password
if archive_cmd == "rar" and is_encrypted then
cmd_password = archive_header_arg .. output_password -- Add archive arg for rar
end
table.insert(archive_args, cmd_password)
end
end
-- Add header arg if selected for 7z
if is_encrypted and archive_header_arg ~= "" and archive_cmd ~= "rar" then
table.insert(archive_args, archive_header_arg)
end
-- Add level arg if selected
if archive_level_arg ~= "" and is_level then
local output_level, event =
ya.input(
{
title = string.format("Enter compression level (%s - %s)", archive_level_min, archive_level_max),
pos = {"top-center", y = 3, w = 40}
}
)
if event ~= 1 then
return
end
-- Validate user input for compression level
if
output_level ~= "" and tonumber(output_level) ~= nil and tonumber(output_level) >= archive_level_min and
tonumber(output_level) <= archive_level_max
then
cmd_level =
type(archive_level_arg) == "table" and archive_level_arg[#archive_level_arg] .. output_level or
archive_level_arg .. output_level
local target_args = archive_compress == "" and archive_args or archive_compress_args
if type(archive_level_arg) == "table" then
-- Insert each element of archive_level_arg (except last) into target_args at the correct position
for i = 1, #archive_level_arg - 1 do
table.insert(target_args, i, archive_level_arg[i])
end
table.insert(target_args, #archive_level_arg, cmd_level) -- Add level at the end
else
-- Insert the compression level argument at the start if not a table
table.insert(target_args, 1, cmd_level)
end
else
notify_error("Invalid level specified. Using defaults.", "warn")
end
end
-- Store the original output name for later use
local original_name = output_name
-- If compression is needed, adjust the output name to exclude extensions like ".tar"
if archive_compress ~= "" then
output_name = output_name:match("(.*%.tar)") or output_name
end
-- Create a temporary directory for intermediate files
local temp_dir_name = ".tmp_compress"
local temp_dir = combine_url(output_dir, temp_dir_name)
local temp_dir, _ = tostring(fs.unique_name(Url(temp_dir)))
-- Attempt to create the temporary directory
local temp_dir_status, temp_dir_err = fs.create("dir_all", Url(temp_dir))
if not temp_dir_status then
-- Notify the user if the temporary directory creation fails
notify_error(string.format("Failed to create temp directory, error code: %s", temp_dir_err), "error")
return
end
-- Define the temporary output file path within the temporary directory
local temp_output_url = combine_url(temp_dir, output_name)
-- Add files to the output archive
for filepath, filenames in pairs(path_fnames) do
-- Execute the archive command for each path and its respective files
local archive_status, archive_err =
Command(archive_cmd):arg(archive_args):arg(temp_output_url):arg(filenames):cwd(filepath):spawn():wait()
if not archive_status or not archive_status.success then
-- Notify the user if the archiving process fails and clean up the temporary directory
notify_error(string.format("Failed to create archive %s with '%s', error: %s", output_name, archive_cmd, archive_err), "error")
local cleanup_status, cleanup_err = fs.remove("dir_all", Url(temp_dir))
if not cleanup_status then
notify_error(string.format("Failed to clean up temporary directory %s, error: %s", temp_dir, cleanup_err), "error")
end
return
end
end
-- If compression is required, execute the compression command
if archive_compress ~= "" then
local compress_status, compress_err =
Command(archive_compress):arg(archive_compress_args):arg(temp_output_url):spawn():wait()
if not compress_status or not compress_status.success then
-- Notify the user if the compression process fails and clean up the temporary directory
notify_error(string.format("Failed to compress archive %s with '%s', error: %s", output_name, archive_compress, compress_err), "error")
local cleanup_status, cleanup_err = fs.remove("dir_all", Url(temp_dir))
if not cleanup_status then
notify_error(string.format("Failed to clean up temporary directory %s, error: %s", temp_dir, cleanup_err), "error")
end
return
end
end
-- Move the final file from the temporary directory to the output directory
local final_output_url, temp_url_processed = combine_url(output_dir, original_name), combine_url(temp_dir, original_name)
final_output_url, _ = tostring(fs.unique_name(Url(final_output_url)))
local move_status, move_err = os.rename(temp_url_processed, final_output_url)
if not move_status then
-- Notify the user if the move operation fails and clean up the temporary directory
notify_error(string.format("Failed to move %s to %s, error: %s", temp_url_processed, final_output_url, move_err), "error")
local cleanup_status, cleanup_err = fs.remove("dir_all", Url(temp_dir))
if not cleanup_status then
notify_error(string.format("Failed to clean up temporary directory %s, error: %s", temp_dir, cleanup_err), "error")
end
return
end
-- Cleanup the temporary directory after successful operation
local cleanup_status, cleanup_err = fs.remove("dir_all", Url(temp_dir))
if not cleanup_status then
notify_error(string.format("Failed to clean up temporary directory %s, error: %s", temp_dir, cleanup_err), "error")
end
end
}

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 yazi-rs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,32 @@
# full-border.yazi
Add a full border to Yazi to make it look fancier.
![full-border](https://github.com/yazi-rs/plugins/assets/17523360/ef81b560-2465-4d36-abf2-5d21dcb7b987)
## Installation
```sh
ya pkg add yazi-rs/plugins:full-border
```
## Usage
Add this to your `init.lua` to enable the plugin:
```lua
require("full-border"):setup()
```
Or you can customize the border type:
```lua
require("full-border"):setup {
-- Available values: ui.Border.PLAIN, ui.Border.ROUNDED
type = ui.Border.ROUNDED,
}
```
## License
This plugin is MIT-licensed. For more information check the [LICENSE](LICENSE) file.

View file

@ -0,0 +1,43 @@
--- @since 25.2.26
local function setup(_, opts)
local type = opts and opts.type or ui.Border.ROUNDED
local old_build = Tab.build
Tab.build = function(self, ...)
local bar = function(c, x, y)
if x <= 0 or x == self._area.w - 1 or th.mgr.border_symbol ~= "" then
return ui.Bar(ui.Edge.TOP)
end
return ui.Bar(ui.Edge.TOP)
:area(
ui.Rect { x = x, y = math.max(0, y), w = ya.clamp(0, self._area.w - x, 1), h = math.min(1, self._area.h) }
)
:symbol(c)
end
local c = self._chunks
self._chunks = {
c[1]:pad(ui.Pad.y(1)),
c[2]:pad(ui.Pad(1, c[3].w > 0 and 0 or 1, 1, c[1].w > 0 and 0 or 1)),
c[3]:pad(ui.Pad.y(1)),
}
local style = th.mgr.border_style
self._base = ya.list_merge(self._base or {}, {
ui.Border(ui.Edge.ALL):area(self._area):type(type):style(style),
ui.Bar(ui.Edge.RIGHT):area(self._chunks[1]):style(style),
ui.Bar(ui.Edge.LEFT):area(self._chunks[3]):style(style),
bar("", c[1].right - 1, c[1].y),
bar("", c[1].right - 1, c[1].bottom - 1),
bar("", c[2].right, c[2].y),
bar("", c[2].right, c[2].bottom - 1),
})
old_build(self, ...)
end
end
return { setup = setup }

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 yazi-rs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,78 @@
# git.yazi
Show the status of Git file changes as linemode in the file list.
https://github.com/user-attachments/assets/34976be9-a871-4ffe-9d5a-c4cdd0bf4576
## Installation
```sh
ya pkg add yazi-rs/plugins:git
```
## Setup
Add the following to your `~/.config/yazi/init.lua`:
```lua
require("git"):setup()
```
And register it as fetchers in your `~/.config/yazi/yazi.toml`:
```toml
[[plugin.prepend_fetchers]]
id = "git"
url = "*"
run = "git"
[[plugin.prepend_fetchers]]
id = "git"
url = "*/"
run = "git"
```
## Advanced
> [!NOTE]
> The following configuration must be put before `require("git"):setup()`
You can customize the [Style](https://yazi-rs.github.io/docs/plugins/layout#style) of the status sign with:
- `th.git.modified`
- `th.git.added`
- `th.git.untracked`
- `th.git.ignored`
- `th.git.deleted`
- `th.git.updated`
For example:
```lua
-- ~/.config/yazi/init.lua
th.git = th.git or {}
th.git.modified = ui.Style():fg("blue")
th.git.deleted = ui.Style():fg("red"):bold()
```
You can also customize the text of the status sign with:
- `th.git.modified_sign`
- `th.git.added_sign`
- `th.git.untracked_sign`
- `th.git.ignored_sign`
- `th.git.deleted_sign`
- `th.git.updated_sign`
For example:
```lua
-- ~/.config/yazi/init.lua
th.git = th.git or {}
th.git.modified_sign = "M"
th.git.deleted_sign = "D"
```
## License
This plugin is MIT-licensed. For more information check the [LICENSE](LICENSE) file.

View file

@ -0,0 +1,255 @@
--- @since 25.12.29
local WINDOWS = ya.target_family() == "windows"
-- The code of supported git status,
-- also used to determine which status to show for directories when they contain different statuses
-- see `bubble_up`
---@enum CODES
local CODES = {
excluded = 100, -- ignored directory
ignored = 6, -- ignored file
untracked = 5,
modified = 4,
added = 3,
deleted = 2,
updated = 1,
unknown = 0,
}
local PATTERNS = {
{ "!$", CODES.ignored },
{ "?$", CODES.untracked },
{ "[MT]", CODES.modified },
{ "[AC]", CODES.added },
{ "D", CODES.deleted },
{ "U", CODES.updated },
{ "[AD][AD]", CODES.updated },
}
---@param line string
---@return CODES, string
local function match(line)
local signs = line:sub(1, 2)
for _, p in ipairs(PATTERNS) do
local path, pattern, code = nil, p[1], p[2]
if signs:find(pattern) then
path = line:sub(4, 4) == '"' and line:sub(5, -2) or line:sub(4)
path = WINDOWS and path:gsub("/", "\\") or path
end
if not path then
elseif path:find("[/\\]$") then
-- Mark the ignored directory as `excluded`, so we can process it further within `propagate_down`
return code == CODES.ignored and CODES.excluded or code, path:sub(1, -2)
else
return code, path
end
---@diagnostic disable-next-line: missing-return
end
end
---@param cwd Url
---@return string?
local function root(cwd)
local is_worktree = function(url)
local file, head = io.open(tostring(url)), nil
if file then
head = file:read(8)
file:close()
end
return head == "gitdir: "
end
repeat
local next = cwd:join(".git")
local cha = fs.cha(next)
if cha and (cha.is_dir or is_worktree(next)) then
return tostring(cwd)
end
cwd = cwd.parent
until not cwd
end
---@param changed Changes
---@return Changes
local function bubble_up(changed)
local new, empty = {}, Url("")
for path, code in pairs(changed) do
if code ~= CODES.ignored then
local url = Url(path).parent
while url and url ~= empty do
local s = tostring(url)
new[s] = (new[s] or CODES.unknown) > code and new[s] or code
url = url.parent
end
end
end
return new
end
---@param excluded string[]
---@param cwd Url
---@param repo Url
---@return Changes
local function propagate_down(excluded, cwd, repo)
local new, rel = {}, cwd:strip_prefix(repo)
for _, path in ipairs(excluded) do
if rel:starts_with(path) then
-- If `cwd` is a subdirectory of an excluded directory, also mark it as `excluded`
new[tostring(cwd)] = CODES.excluded
elseif cwd == repo:join(path).parent then
-- If `path` is a direct subdirectory of `cwd`, mark it as `ignored`
new[path] = CODES.ignored
else
-- Skipping, we only care about `cwd` itself and its direct subdirectories for maximum performance
end
end
return new
end
---@param cwd string
---@param repo string
---@param changed Changes
local add = ya.sync(function(st, cwd, repo, changed)
---@cast st State
st.dirs[cwd] = repo
st.repos[repo] = st.repos[repo] or {}
for path, code in pairs(changed) do
if code == CODES.unknown then
st.repos[repo][path] = nil
elseif code == CODES.excluded then
-- Mark the directory with a special value `excluded` so that it can be distinguished during UI rendering
st.dirs[path] = CODES.excluded
else
st.repos[repo][path] = code
end
end
ui.render()
end)
---@param cwd string
local remove = ya.sync(function(st, cwd)
---@cast st State
local repo = st.dirs[cwd]
if not repo then
return
end
ui.render()
st.dirs[cwd] = nil
if not st.repos[repo] then
return
end
for _, r in pairs(st.dirs) do
if r == repo then
return
end
end
st.repos[repo] = nil
end)
---@param st State
---@param opts Options
local function setup(st, opts)
st.dirs = {}
st.repos = {}
opts = opts or {}
opts.order = opts.order or 1500
local t = th.git or {}
local styles = {
[CODES.ignored] = t.ignored and ui.Style(t.ignored) or ui.Style():fg("darkgray"),
[CODES.untracked] = t.untracked and ui.Style(t.untracked) or ui.Style():fg("magenta"),
[CODES.modified] = t.modified and ui.Style(t.modified) or ui.Style():fg("yellow"),
[CODES.added] = t.added and ui.Style(t.added) or ui.Style():fg("green"),
[CODES.deleted] = t.deleted and ui.Style(t.deleted) or ui.Style():fg("red"),
[CODES.updated] = t.updated and ui.Style(t.updated) or ui.Style():fg("yellow"),
}
local signs = {
[CODES.ignored] = t.ignored_sign or "",
[CODES.untracked] = t.untracked_sign or "? ",
[CODES.modified] = t.modified_sign or "",
[CODES.added] = t.added_sign or "",
[CODES.deleted] = t.deleted_sign or "",
[CODES.updated] = t.updated_sign or "",
}
Linemode:children_add(function(self)
if not self._file.in_current then
return ""
end
local url = self._file.url
local repo = st.dirs[tostring(url.base or url.parent)]
local code
if repo then
code = repo == CODES.excluded and CODES.ignored or st.repos[repo][tostring(url):sub(#repo + 2)]
end
if not code or signs[code] == "" then
return ""
elseif self._file.is_hovered then
return ui.Line { " ", signs[code] }
else
return ui.Line { " ", ui.Span(signs[code]):style(styles[code]) }
end
end, opts.order)
end
---@type UnstableFetcher
local function fetch(_, job)
local cwd = job.files[1].url.base or job.files[1].url.parent
local repo = root(cwd)
if not repo then
remove(tostring(cwd))
return true
end
local paths = {}
for _, file in ipairs(job.files) do
paths[#paths + 1] = tostring(file.url)
end
-- stylua: ignore
local output, err = Command("git")
:cwd(tostring(cwd))
:arg({ "--no-optional-locks", "-c", "core.quotePath=", "status", "--porcelain", "-unormal", "--no-renames", "--ignored=matching" })
:arg(paths)
:stdout(Command.PIPED)
:output()
if not output then
return true, Err("Cannot spawn `git` command, error: %s", err)
end
local changed, excluded = {}, {}
for line in output.stdout:gmatch("[^\r\n]+") do
local code, path = match(line)
if code == CODES.excluded then
excluded[#excluded + 1] = path
else
changed[path] = code
end
end
if job.files[1].cha.is_dir then
ya.dict_merge(changed, bubble_up(changed))
end
ya.dict_merge(changed, propagate_down(excluded, cwd, Url(repo)))
-- Reset the status of any files that don't appear in the output of `git status` to `unknown`,
-- so that cleaning up outdated statuses from `st.repos`
for _, path in ipairs(paths) do
local s = path:sub(#repo + 2)
changed[s] = changed[s] or CODES.unknown
end
add(tostring(cwd), repo, changed)
return false
end
return { setup = setup, fetch = fetch }

View file

@ -0,0 +1,12 @@
---@class State
---@field dirs table<string, string|CODES> Mapping between a directory and its corresponding repository
---@field repos table<string, Changes> Mapping between a repository and the status of each of its files
---@class Options
---@field order number The order in which the status is displayed
---@field renamed boolean Whether to include renamed files in the status (or treat them as modified)
-- TODO: move this to `types.yazi` once it's get stable
---@alias UnstableFetcher fun(self: unknown, job: { files: File[] }): boolean, Error?
---@alias Changes table<string, CODES>

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 walldmtd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,41 @@
# krita-preview.yazi
A [Yazi](https://github.com/sxyazi/yazi) plugin to preview Krita's .kra and
.kra~ files.
> [!TIP]
> Krita's thumbnails are limited to 256x256 pixels.
> [zoom.yazi](https://github.com/yazi-rs/plugins/tree/main/zoom.yazi) can help
increase the size, but won't change the resolution.
## Requirements
Either `unzip` or `7z` need to be installed and available in the PATH.
## Installation
```sh
ya pkg add walldmtd/krita-preview
```
## Usage
Add this to `yazi.toml`:
```toml
[plugin]
prepend_preloaders = [
{ name = "*.kra", run = "krita-preview" },
{ name = "*.kra~", run = "krita-preview" },
]
prepend_previewers = [
{ name = "*.kra", run = "krita-preview" },
{ name = "*.kra~", run = "krita-preview" },
]
```
## Acknowledgements
- [Yazi](https://github.com/sxyazi/yazi), for
[magick.lua](https://github.com/sxyazi/yazi/blob/main/yazi-plugin/preset/plugins/magick.lua)
(used as a base for this plugin)

View file

@ -0,0 +1,56 @@
local M = {}
function M:peek(job)
local start, cache = os.clock(), ya.file_cache(job)
if not cache then
return
end
local ok, err = self:preload(job)
if not ok or err then
return ya.preview_widget(job, err)
end
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err)
end
function M:seek() end
function M:preload(job)
local cache = ya.file_cache(job)
if not cache or fs.cha(cache) then
return true
end
local cmd_unzip = Command("unzip"):arg({ "-jp", tostring(job.file.url), "preview.png" })
local cmd_7z = Command("7z"):arg({ "e", "-so", tostring(job.file.url), "preview.png" })
local output = cmd_unzip:output()
if not output then
-- Try with `7z` instead
output = cmd_7z:output()
if not output then
return nil, Err("Failed to start `unzip` or `7z`")
elseif not output.status.success then
return nil, Err("`7z` exited with error code: %s", output.status.code)
end
elseif not output.status.success then
return nil, Err("`unzip` exited with error code: %s", output.status.code)
end
local ok, err = fs.write(cache, output.stdout)
if not ok then
return false, Err("Failed to write preview image to cache, error: %s", err)
else
return true
end
end
function M:spot(job)
require("file"):spot(job)
end
return M

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 greg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,18 @@
# mdcat.yazi
Preview markdown files in [yazi](https://github.com/sxyazi/yazi) with [mdcat](https://github.com/swsnr/mdcat).
Install this plugin with:
```bash
ya pack --add GrzegorzKozub/mdcat
```
Then set it up in your `yazi.toml` file by adding:
```toml
[plugin]
prepend_previewers = [
{ name = "*.md", run = "mdcat" },
]
```

View file

@ -0,0 +1,47 @@
local M = {}
function M:peek(job)
local child = Command('mdcat')
:args({
'--columns',
tostring(job.area.w),
tostring(job.file.url),
})
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:spawn()
local count, lines = 0, ''
repeat
local line, event = child:read_line()
if event ~= 0 then
break
else
count = count + 1
if count > job.skip then
lines = lines .. line
end
end
until count >= job.skip + job.area.h
child:start_kill()
if job.skip > 0 and count < job.skip + job.area.h then
ya.manager_emit('peek', {
tostring(math.max(0, count - job.area.h)),
only_if = job.file.url,
upper_bound = '',
})
else
ya.preview_widgets(job, { ui.Text.parse(lines):area(job.area) })
end
end
function M:seek(job)
local h = cx.active.current.hovered
if h and h.url == job.file.url then
ya.manager_emit('peek', {
math.max(0, cx.active.preview.skip + job.units),
only_if = job.file.url,
})
end
end
return M

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 yazi-rs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,56 @@
# mime-ext.yazi
A mime-type provider based on a file extension database, replacing the [builtin `file(1)`](https://github.com/sxyazi/yazi/blob/main/yazi-plugin/preset/plugins/mime.lua) to speed up mime-type retrieval at the expense of accuracy.
See https://yazi-rs.github.io/docs/tips#make-yazi-even-faster for more information.
## Installation
```sh
ya pkg add yazi-rs/plugins:mime-ext
```
## Usage
Add this to your `~/.config/yazi/yazi.toml`:
```toml
[[plugin.prepend_fetchers]]
id = "mime"
url = "*"
run = "mime-ext"
prio = "high"
```
## Advanced
You can also customize it in your `~/.config/yazi/init.lua` with:
```lua
require("mime-ext"):setup {
-- Expand the existing filename database (lowercase), for example:
with_files = {
makefile = "text/makefile",
-- ...
},
-- Expand the existing extension database (lowercase), for example:
with_exts = {
mk = "text/makefile",
-- ...
},
-- If the mime-type is not in both filename and extension databases,
-- then fallback to Yazi's preset `mime` plugin, which uses `file(1)`
fallback_file1 = false,
}
```
## TODO
- Add more file types (PRs welcome!).
- Compress mime-type tables.
## License
This plugin is MIT-licensed. For more information check the [LICENSE](LICENSE) file.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 yazi-rs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,76 @@
<div align="center">
# office.yazi
### A plugin to preview office documents in <a href="https://github.com/sxyazi/yazi">Yazi <img src="https://github.com/sxyazi/yazi/blob/main/assets/logo.png?raw=true" alt="a duck" width="24px" height="24px"></a>
<img src="https://github.com/macydnah/office.yazi/blob/assets/preview_test.gif" alt="preview test" width="88%">
##
</div>
## Installation
> [!TIP]
> Installing this plugin with `ya` will conveniently clone the plugin from GitHub,
> copy it to your plugins directory, and update the `package.toml` to lock its version [^1].
>
> To install it with `ya` run:
> ```sh
> ya pkg add macydnah/office
> ```
> Or if you prefer a manual approach:
> ```sh
> ## For linux and MacOS
> git clone https://github.com/macydnah/office.yazi.git ~/.config/yazi/plugins/office.yazi
>
> ## For Windows
> git clone https://github.com/macydnah/office.yazi.git %AppData%\yazi\config\plugins\office.yazi
> ```
## Usage
In your `yazi.toml` add rules to preloaders[^2] and previewers[^3] to run `office` plugin with office documents.
> [!NOTE]
> Your config may be different depending if you're *appending*, *prepending* or *overriding* default rules.
> If unsure, take a look at [Configuration](https://yazi-rs.github.io/docs/configuration/overview)[^4]
> and [Configuration mixing](https://yazi-rs.github.io/docs/configuration/overview#mixing)[^5]
For a general usecase, you may use the following rules
```toml
[plugin]
prepend_preloaders = [
# Office Documents
{ mime = "application/openxmlformats-officedocument.*", run = "office" },
{ mime = "application/oasis.opendocument.*", run = "office" },
{ mime = "application/ms-*", run = "office" },
{ mime = "application/msword", run = "office" },
{ name = "*.docx", run = "office" },
]
prepend_previewers = [
# Office Documents
{ mime = "application/openxmlformats-officedocument.*", run = "office" },
{ mime = "application/oasis.opendocument.*", run = "office" },
{ mime = "application/ms-*", run = "office" },
{ mime = "application/msword", run = "office" },
{ name = "*.docx", run = "office" },
]
```
## Dependencies
> [!IMPORTANT]
> Make sure that these commands are installed in your system and can be found in `PATH`:
>
> - `libreoffice`
> - `pdftoppm`
## License
office.yazi is licensed under the terms of the [MIT License](LICENSE)
[^1]: [The official package manager for Yazi](https://yazi-rs.github.io/docs/cli)
[^2]: [Preloaders rules](https://yazi-rs.github.io/docs/configuration/yazi#plugin.preloaders)
[^3]: [Previewers rules](https://yazi-rs.github.io/docs/configuration/yazi#plugin.previewers)
[^4]: [Configuration](https://yazi-rs.github.io/docs/configuration/overview)
[^5]: [Configuration mixing](https://yazi-rs.github.io/docs/configuration/overview#mixing)

View file

@ -0,0 +1,114 @@
--- @since 25.2.7
local M = {}
function M:peek(job)
local start, cache = os.clock(), ya.file_cache(job)
if not cache then
return
end
local ok, err = self:preload(job)
if not ok or err then
return
end
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
ya.image_show(cache, job.area)
ya.preview_widgets(job, {})
end
function M:seek(job)
local h = cx.active.current.hovered
if h and h.url == job.file.url then
local step = ya.clamp(-1, job.units, 1)
ya.manager_emit("peek", { math.max(0, cx.active.preview.skip + step), only_if = job.file.url })
end
end
function M:doc2pdf(job)
local tmp = "/tmp/yazi-" .. ya.uid() .. "/" .. ya.hash("office.yazi") .. "/"
--[[ For Future Reference: Regarding `libreoffice` as preconverter
1. It prints errors to stdout (always, doesn't matter if it succeeded or it failed)
2. Always writes the converted files to the filesystem, so no "Mario|Bros|Piping|Magic" for the data stream (https://ask.libreoffice.org/t/using-convert-to-output-to-stdout/38753)
3. The `pdf:draw_pdf_Export` filter needs literal double quotes when defining its options (https://help.libreoffice.org/latest/en-US/text/shared/guide/pdf_params.html?&DbPAR=SHARED&System=UNIX#generaltext/shared/guide/pdf_params.xhp)
3.1 Regarding double quotes and Lua strings, see https://www.lua.org/manual/5.1/manual.html#2.1 --]]
local libreoffice = Command("libreoffice")
:arg({
"--headless",
"--convert-to",
'pdf:draw_pdf_Export:{"PageRange":{"type":"string","value":"' .. job.skip + 1 .. '"}}',
"--outdir",
tmp,
tostring(job.file.url),
})
:stdin(Command.NULL)
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:output()
if not libreoffice.status.success then
local output = libreoffice.stdout .. libreoffice.stderr
local version = (output:match("LibreOffice .+") or ""):gsub("%\n.*", "")
local error = (output:match("Error:? .+") or ""):gsub("%\n.*", "")
if version ~= "" or error ~= "" then
ya.err((version or "LibreOffice") .. " " .. (error or "Unknown error"))
end
return nil, Err("Failed to preconvert `%s` to a temporary PDF", job.file.name)
end
local tmp = tmp .. job.file.name:gsub("%.[^%.]+$", ".pdf")
local read_permission = io.open(tmp, "r")
if not read_permission then
return nil, Err("Failed to read `%s`: make sure file exists and have read access", tmp)
end
read_permission:close()
return tmp
end
function M:preload(job)
local cache = ya.file_cache(job)
if not cache or fs.cha(cache) then
return true
end
local tmp_pdf, err = self:doc2pdf(job)
if not tmp_pdf then
return true, Err(" " .. "%s", err)
end
local output, err = Command("pdftoppm")
:arg({
"-singlefile",
"-jpeg",
"-jpegopt",
"quality=" .. rt.preview.image_quality,
"-f",
1,
tostring(tmp_pdf),
})
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:output()
local rm_tmp_pdf, rm_err = fs.remove("file", Url(tmp_pdf))
if not rm_tmp_pdf then
return true, Err("Failed to remove %s, error: %s", tmp_pdf, rm_err)
end
if not output then
return true, Err("Failed to start `pdftoppm`, error: %s", err)
elseif not output.status.success then
local pages = tonumber(output.stderr:match("the last page %((%d+)%)")) or 0
if job.skip > 0 and pages > 0 then
ya.mgr_emit("peek", { math.max(0, pages - 1), only_if = job.file.url, upper_bound = true })
end
return true, Err("Failed to convert %s to image, stderr: %s", tmp_pdf, output.stderr)
end
return fs.write(cache, output.stdout)
end
return M

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 ndtoan96
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,92 @@
# ouch.yazi
[ouch](https://github.com/ouch-org/ouch) plugin for [Yazi](https://github.com/sxyazi/yazi).
![ouch.yazi](https://github.com/ndtoan96/ouch.yazi/assets/33489972/946397ec-b37b-4bf4-93f1-c676fc8e59f2)
## Features
- Archive preview
- Compression
## Installation
### Yazi package manager
```bash
ya pkg add ndtoan96/ouch
```
### Git
```bash
# Linux/macOS
git clone https://github.com/ndtoan96/ouch.yazi.git ~/.config/yazi/plugins/ouch.yazi
# Windows with cmd
git clone https://github.com/ndtoan96/ouch.yazi.git %AppData%\yazi\config\plugins\ouch.yazi
# Windows with powershell
git clone https://github.com/ndtoan96/ouch.yazi.git "$($env:APPDATA)\yazi\config\plugins\ouch.yazi"
```
Make sure you have [ouch](https://github.com/ouch-org/ouch) installed and in your `PATH`.
## Usage
### Preview
For archive preview, add this to your `yazi.toml`:
```toml
[[plugin.prepend_previewers]]
mime = "application/{*zip,tar,bzip2,7z*,rar,xz,zstd,java-archive}"
run = "ouch"
```
Now go to an archive on Yazi, you should see the archive's content in the preview pane. You can use `J` and `K` to roll up and down the preview.
#### Customization
Previews can be customized by adding extra arguments in the `run` string:
```toml
[plugin]
prepend_previewers = [
# Change the top-level archive icon
{ ..., run = "ouch --archive-icon='🗄️ '" },
# Or remove it by setting it to ''
{ ..., run = "ouch --archive-icon=''" },
# Enable file icons
{ ..., run = "ouch --show-file-icons" },
# Disable tree view
{ ..., run = "ouch --list-view" },
# These can be combined
{ ..., run = "ouch --archive-icon='🗄️ ' --show-file-icons --list-view" },
]
```
### Compression
For compession, add this to your `keymap.toml`:
```toml
[[mgr.prepend_keymap]]
on = ["C"]
run = "plugin ouch"
desc = "Compress with ouch"
```
The plugin uses `zip` format by default. You can change the format when you name the output file, `ouch` will detect format based on file extension.
And, for example, if you would like to set `7z` as default format, you can use `plugin ouch 7z`.
### Decompression
This plugin does not provide a decompression feature because it already is supported by Yazi.
To decompress with `ouch`, configure the opener in `yazi.toml`.
```toml
[opener]
extract = [
{ run = 'ouch d -y %*', desc = "Extract here with ouch", for = "windows" },
{ run = 'ouch d -y "$@"', desc = "Extract here with ouch", for = "unix" },
]
```

View file

@ -0,0 +1,195 @@
local M = {}
-- Extract the tree prefix (if any) from a line
local function get_tree_prefix(line)
local _, prefix_len = line:find("", 1, true)
if prefix_len then
return line:sub(1, prefix_len)
else
return ""
end
end
-- Add a filetype icon to a line
local function line_with_icon(line)
line = line:gsub("[\r\n]+$", "") -- Trailing newlines mess with filetype detection
local tree_prefix = get_tree_prefix(line)
local url = line:sub(#tree_prefix + 1)
local icon = File({
url = Url(url),
cha = Cha {
mode = tonumber(url:sub(-1) == "/" and "40700" or "100644", 8),
kind = url:sub(-1) == "/" and 1 or 0, -- For Yazi <25.9.x compatibility
}
}):icon()
if icon then
line = ui.Line { tree_prefix, ui.Span(icon.text .. " "):style(icon.style), url }
end
return line
end
function M:peek(job)
local cmd = Command("ouch"):arg("l")
if not job.args.list_view then
cmd:arg("-t")
end
cmd:arg({ "-y", tostring(job.file.url) })
:stdout(Command.PIPED)
:stderr(Command.PIPED)
local child = cmd:spawn()
local limit = job.area.h
local archive_icon = job.args.archive_icon or "\u{1f4c1} "
local file_name = string.match(tostring(job.file.url), ".*[/\\](.*)")
local lines = { string.format(" %s%s", archive_icon, file_name) }
local num_skip = 0
repeat
local line, event = child:read_line()
if event == 1 then
ya.err(tostring(event))
elseif event ~= 0 then
break
end
if line:find('Archive', 1, true) ~= 1 and line:find('[INFO]', 1, true) ~= 1 then
if num_skip >= job.skip then
if job.args.show_file_icons then
if line:find ('[ERROR]', 1, true) == 1 then
-- On error, disable file icons for the rest of the output
job.args.show_file_icons = false
elseif line:find ('[WARNING]', 1, true) ~= 1 then
-- Show icons for non-warning lines only
line = line_with_icon(line)
end
end
line = ui.Line { " ", line } -- One space padding
table.insert(lines, line)
else
num_skip = num_skip + 1
end
end
until #lines >= limit
child:start_kill()
if job.skip > 0 and #lines < limit then
ya.emit(
"peek",
{ tostring(math.max(0, job.skip - (limit - #lines))), only_if = tostring(job.file.url), upper_bound = "" }
)
else
ya.preview_widget(job, { ui.Text(lines):area(job.area) })
end
end
function M:seek(job)
local h = cx.active.current.hovered
if h and h.url == job.file.url then
local step = math.floor(job.units * job.area.h / 10)
ya.emit("peek", {
math.max(0, cx.active.preview.skip + step),
only_if = tostring(job.file.url),
})
end
end
-- Check if file exists
local function file_exists(name)
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Get the files that need to be compressed and infer a default archive name
local get_compression_target = ya.sync(function()
local tab = cx.active
local default_name
local paths = {}
if #tab.selected == 0 then
if tab.current.hovered then
local name = tab.current.hovered.name
default_name = name
table.insert(paths, name)
else
return
end
else
default_name = tab.current.cwd.name
for _, url in pairs(tab.selected) do
table.insert(paths, tostring(url))
end
-- The compression targets are aquired, now unselect them
ya.emit("escape", {})
end
return paths, default_name
end)
local function invoke_compress_command(paths, name)
local cmd_output, err_code = Command("ouch")
:arg({ "c", "-y" })
:arg(paths)
:arg(name)
:stderr(Command.PIPED)
:output()
if err_code ~= nil then
ya.notify({
title = "Failed to run ouch command",
content = "Status: " .. err_code,
timeout = 5.0,
level = "error",
})
elseif not cmd_output.status.success then
ya.notify({
title = "Compression failed: status code " .. cmd_output.status.code,
content = cmd_output.stderr,
timeout = 5.0,
level = "error",
})
end
end
function M:entry(job)
local default_fmt = job.args[1]
if default_fmt == nil then
default_fmt = "zip"
end
ya.emit("escape", { visual = true })
-- Get the files that need to be compressed and infer a default archive name
local paths, default_name = get_compression_target()
-- Get archive name from user
local output_name, name_event = ya.input({
title = "Create archive:",
value = default_name .. "." .. default_fmt,
position = { "top-center", y = 3, w = 40 },
pos = { "top-center", y = 3, w = 40 },
})
if name_event ~= 1 then
return
end
-- Get confirmation if file exists
if file_exists(output_name) then
local confirm, confirm_event = ya.input({
title = "Overwrite " .. output_name .. "? (y/N)",
position = { "top-center", y = 3, w = 40 },
pos = { "top-center", y = 3, w = 40 },
})
if not (confirm_event == 1 and confirm:lower() == "y") then
return
end
end
invoke_compress_command(paths, output_name)
end
return M

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -0,0 +1,27 @@
<img width="1920" height="1080" alt="preview of alubum art and some audio metadata" src="https://github.com/user-attachments/assets/731bd9b8-b963-43c9-866e-4250885d0bbe" />
# Installation
```sh
ya pkg add AminurAlam/yazi-plugins:preview-audio
```
# Dependencies
- `ffmpeg`
# Usage
in `~/.config/yazi/yazi.toml`
```toml
[plugin]
prepend_previewers = [
{ mime = 'audio/mpegurl', run = 'code' }, # ignore .m3u files
{ mime = 'audio/*', run = 'preview-audio' },
]
prepend_preloaders = [
{ mime = 'audio/mpegurl', run = 'code' }, # ignore .m3u files
{ mime = 'audio/*', run = 'preview-audio' },
]
```

View file

@ -0,0 +1,130 @@
--- @since 25.12.29
local M = {}
local audio_ffprobe = function(file)
-- stylua: ignore
local cmd = Command('ffprobe'):arg {
'-v', 'quiet',
'-show_entries', 'stream_tags:format:stream',
'-of', 'json=c=1',
file.name
}
local output, err = cmd:output()
if not output then
return {}, Err('Failed to start `ffprobe`, error: %s', err)
end
local json = ya.json_decode(output.stdout)
if not json then
return nil, Err('Failed to decode `ffprobe` output: %s', output.stdout)
elseif type(json) ~= 'table' then
return nil, Err('Invalid `ffprobe` output: %s', output.stdout)
end
ya.dbg(json)
local stream = json.streams[1]
local tags = json.format.tags or stream.tags or stream
local data = {}
local title, album, aar, ar =
tags.TITLE or tags.title or '',
tags.ALBUM or tags.album or '',
tags.ALBUM_ARTIST or tags.album_artist or '',
tags.ARTIST or tags.artist or ''
if title .. album .. ar .. aar ~= '' then
local cdata = json.streams[2]
local date = tags.DATE or tags.date or ''
local c = ''
local artist = ar
if tags.ORIGINALDATE and tags.ORIGINALDATE ~= '' then
date = date .. ' / ' .. tags.ORIGINALDATE
end
if (aar ~= '') and (aar ~= ar) then
artist = artist .. ' / ' .. aar
end
if cdata then
c = cdata.codec_name .. ' ' .. cdata.width .. 'x' .. cdata.height
end
data = {
ui.Line(string.format('%s - %s', artist, title)),
ui.Line(string.format('%s: %s', 'Album', album)),
ui.Line(string.format('%s: %s', 'Genre', tags.GENRE or tags.genre)),
ui.Line(string.format('%s: %s', 'Date', date)),
c ~= '' and ui.Line(string.format('%s: %s', 'Cover art', c)) or nil,
}
end
local br = tonumber((json.format.bit_rate or 0) // 1000) .. ' kb/s'
table.insert(data, ui.Line(string.format('%s: %s', 'Format', json.format.format_name)))
table.insert(data, ui.Line(string.format('%s: %s', 'BitRate', br)))
table.insert(data, ui.Line(string.format('%s: %s', 'Channels', tostring(stream.channels or '?'))))
return data
end
function M:peek(job)
local start, cache = os.clock(), ya.file_cache(job)
local ok, err = self:preload(job)
local img_area
if cache and fs.cha(cache) then
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
img_area, err = ya.image_show(cache, job.area)
end
ya.preview_widget(job, {
ui.Text(audio_ffprobe(job.file)):area(ui.Rect {
x = job.area.x,
y = job.area.y + (img_area and img_area.h or 0),
w = job.area.w,
h = job.area.h,
}),
})
end
function M:seek(job) end
function M:preload(job)
local cache = ya.file_cache(job)
if not cache then
return true
end
local cha = fs.cha(cache)
if cha and cha.len > 0 then
return true
end
-- stylua: ignore
local output, err = Command('ffmpeg')
:arg({
'-hide_banner',
'-loglevel', 'warning',
'-i', tostring(job.file.url),
'-an',
-- '-vcodec', 'copy',
string.format('%s.jpg', cache),
})
:stderr(Command.PIPED)
:output()
if not output then
return true, Err('Failed to start `ffmpeg`, error: %s', err)
elseif not output.status.success then
return true, Err('Failed to get image, stderr: %s', output.stderr)
end
local ok, err = os.rename(string.format('%s.jpg', cache), tostring(cache))
if ok then
return true
else
return true, Err('Failed to rename: %s', err)
end
end
return M

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 yazi-rs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,40 @@
# smart-enter.yazi
[`Open`][open] files or [`enter`][enter] directories all in one key!
## Installation
```sh
ya pkg add yazi-rs/plugins:smart-enter
```
## Usage
Bind your <kbd>l</kbd> key to the plugin, in your `~/.config/yazi/keymap.toml`:
```toml
[[mgr.prepend_keymap]]
on = "l"
run = "plugin smart-enter"
desc = "Enter the child directory, or open the file"
```
## Advanced
By default, `--hovered` is passed to the [`open`][open] command, make the behavior consistent with [`enter`][enter] avoiding accidental triggers,
which means both will only target the currently hovered file.
If you still want `open` to target multiple selected files, add this to your `~/.config/yazi/init.lua`:
```lua
require("smart-enter"):setup {
open_multi = true,
}
```
## License
This plugin is MIT-licensed. For more information check the [LICENSE](LICENSE) file.
[open]: https://yazi-rs.github.io/docs/configuration/keymap/#mgr.open
[enter]: https://yazi-rs.github.io/docs/configuration/keymap/#mgr.enter

View file

@ -0,0 +1,11 @@
--- @since 25.5.31
--- @sync entry
local function setup(self, opts) self.open_multi = opts.open_multi end
local function entry(self)
local h = cx.active.current.hovered
ya.emit(h and h.cha.is_dir and "enter" or "open", { hovered = not self.open_multi })
end
return { entry = entry, setup = setup }

View file

@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

View file

@ -0,0 +1,40 @@
# torrent-preview.yazi
[Yazi](https://github.com/sxyazi/yazi) plugin to preview `application/bittorrent` files
![show case](https://github.com/kirasok/torrent-preview.yazi/assets/75790517/6f215e6d-bb19-46f4-b606-9241594028ff)
## Requirements
- [yazi](https://github.com/sxyazi/yazi)
- [transmission-cli](https://github.com/transmission/transmission)
## Installation
### Linux/MacOS
Using the [Yazi Package Manager](https://yazi-rs.github.io/docs/cli/#package-manager):
```sh
ya pack -a kirasok/torrent-preview
```
Or manually:
```sh
git clone https://github.com/kirasok/torrent-preview.yazi.git ~/.config/yazi/plugins/torrent-preview.yazi
```
## Usage
Add this to your `yazi.toml`:
```toml
[[plugin.prepend_previewers]]
mime = "application/bittorrent"
run = "torrent-preview"
```
> [!NOTE]
> Yazi after `v0.4` removes `x-` prefix from subtype, so even if `file -i` outputs `application/x-bittorrent`, you should use `application/bittorrent` ([relevant issue](https://github.com/kirasok/torrent-preview.yazi/issues/2))

View file

@ -0,0 +1,43 @@
local M = {}
function M:peek(job)
local child = Command("transmission-show")
:arg(tostring(job.file.url))
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:spawn()
if not child then
return require("code"):peek(job)
end
local limit = job.area.h
local i, lines = 0, ""
repeat
local next, event = child:read_line()
if event == 1 then
return require("code"):peek(job)
elseif event ~= 0 then
break
end
i = i + 1
if i > job.skip then
lines = lines .. next
end
until i >= job.skip + limit
child:start_kill()
if job.skip > 0 and i < job.skip + limit then
ya.manager_emit("peek", { math.max(0, i - limit), only_if = job.file.url, upper_bound = true })
else
lines = lines:gsub("\t", string.rep(" ", rt.preview.tab_size))
ya.preview_widget(job, { ui.Text.parse(lines):area(job.area) })
end
end
function M:seek(job)
require("code"):seek(job)
end
return M

View file

@ -0,0 +1,43 @@
local M = {}
function M:peek(job)
local child = Command("transmission-show")
:arg(tostring(job.file.url))
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:spawn()
if not child then
return require("code"):peek(job)
end
local limit = job.area.h
local i, lines = 0, ""
repeat
local next, event = child:read_line()
if event == 1 then
return require("code"):peek(job)
elseif event ~= 0 then
break
end
i = i + 1
if i > job.skip then
lines = lines .. next
end
until i >= job.skip + limit
child:start_kill()
if job.skip > 0 and i < job.skip + limit then
ya.manager_emit("peek", { math.max(0, i - limit), only_if = job.file.url, upper_bound = true })
else
lines = lines:gsub("\t", string.rep(" ", rt.preview.tab_size))
ya.preview_widget(job, { ui.Text.parse(lines):area(job.area) })
end
end
function M:seek(job)
require("code"):seek(job)
end
return M