This commit is contained in:
Anton Rogov 2025-06-05 08:36:18 +00:00 committed by GitHub
commit 99aad1303a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 38 additions and 4 deletions

View file

@ -10,7 +10,6 @@
local M = {}
M.__index = M
local NVIM_ID_BITS = 10
local CHUNK_SIZE = 4096
local MAX_FSIZE = 200 * 1024 * 1024 -- 200MB
local _id = 30
@ -57,13 +56,40 @@ function M.new(src)
images[self.file] = self
_id = _id + 1
local bit = require("bit")
local max_id_bits, nvim_id_bits
if Snacks.image.config.cterm256 then
max_id_bits = 16
nvim_id_bits = 4
else
max_id_bits = 32
nvim_id_bits = 10
end
-- generate a unique id for this nvim instance (10 bits)
if nvim_id == 0 then
local pid = vim.fn.getpid()
nvim_id = bit.band(bit.bxor(pid, bit.rshift(pid, 5), bit.rshift(pid, NVIM_ID_BITS)), 0x3FF)
local mask = bit.lshift(1, nvim_id_bits) - 1
nvim_id = bit.band(bit.bxor(pid, bit.rshift(pid, 5), bit.rshift(pid, nvim_id_bits)), mask)
end
-- interleave the nvim id and the image id
self.id = bit.bor(bit.lshift(nvim_id, 24 - NVIM_ID_BITS), _id)
if Snacks.image.config.cterm256 then
local lower = bit.band(_id, 0xff)
local upper = bit.band(bit.rshift(_id, 8), 0xff)
upper = bit.bor(bit.lshift(nvim_id, 8 - nvim_id_bits), upper)
-- upper will be send via a diacritic (bits 24-31), lower is a cterm fg (256 colors)
self.id = bit.bor(bit.lshift(upper, 24), lower)
else
self.id = bit.bor(bit.lshift(nvim_id, max_id_bits - nvim_id_bits), _id)
end
-- TODO: better way to deal with bitwise signed: if bitwise ops set the most significant bit,
-- then the number is treated as negative, but regular math ops do not
if self.id < 0 then
self.id = bit.rshift(self.id, 1) * 2
end
self.placements = {}
self:run()

View file

@ -39,6 +39,7 @@ M.meta = {
---@class snacks.image.Config
---@field enabled? boolean enable image viewer
---@field cterm256? boolean use 256 colors for image ids
---@field wo? vim.wo|{} options for windows showing the image
---@field bo? vim.bo|{} options for the image buffer
---@field formats? string[]

View file

@ -203,12 +203,16 @@ end
--- Renders the unicode placeholder grid in the buffer
---@param loc snacks.image.Loc
function M:render_grid(loc)
local bit = require("bit")
local upper_id = bit.band(bit.rshift(self.img.id, 24), 0xff)
local hl = "SnacksImage" .. self.id -- image id is encoded in the foreground color
Snacks.util.set_hl({
[hl] = {
fg = self.img.id,
fg = bit.band(self.img.id, 0xffffff),
sp = self.id,
bg = Snacks.image.config.debug.placement and "#FF007C" or "none",
ctermfg = bit.band(self.img.id, 0xff),
nocombine = true,
},
})
@ -222,6 +226,9 @@ function M:render_grid(loc)
line[#line + 1] = PLACEHOLDER
line[#line + 1] = positions[r]
line[#line + 1] = positions[c]
if upper_id > 0 then
line[#line + 1] = positions[upper_id + 1]
end
end
img[#img + 1] = table.concat(line)
end