Skip to content

Commit 55ee570

Browse files
committed
feat: allows showing output as virtual text
1 parent 2c32e2f commit 55ee570

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

lua/defaults.lua

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ lang_conf["markdown.pandoc"] = { "```", "```" }
99

1010
M.lang_conf = lang_conf
1111

12+
M.virt_text = false
1213
M.require_confirmation = true
1314
M.allowed_file_types = {}
1415
M.exec_timeout = -1

lua/mdeval.lua

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,22 @@ local function remove_previous_output(linenr)
252252
fn.setpos(".", saved_pos)
253253
end
254254

255+
-- Deletes existing lines in virtual output
256+
-- @param bufnr Buffer number
257+
-- @param ns_id Namespace id
258+
local function remove_virtual_lines(bufnr, ns_id, line_start, line_end)
259+
local existing_marks = vim.api.nvim_buf_get_extmarks(
260+
bufnr,
261+
ns_id,
262+
{line_start, 0},
263+
{line_end, 0},
264+
{}
265+
)
266+
for _, v in pairs(existing_marks) do
267+
vim.api.nvim_buf_del_extmark(bufnr, ns_id, v[1])
268+
end
269+
end
270+
255271
-- Writes output of the excuted command after the linenr line.
256272
-- @param out Table containing lines from the output.
257273
local function write_output(linenr, out)
@@ -278,10 +294,28 @@ local function write_output(linenr, out)
278294
out_table[#out_table + 1] = ""
279295
end
280296

297+
-- Do not use virtual text
298+
if (M.opts.virt_text ~= nil) then
299+
for _, s in pairs(out_table) do
300+
fn.append(linenr, s)
301+
linenr = linenr + 1
302+
end
303+
return
304+
end
305+
306+
-- Use virtual text
307+
local bufnr = vim.api.nvim_get_current_buf()
308+
local ns_id = vim.api.nvim_create_namespace("mdeval")
309+
remove_virtual_lines(bufnr, ns_id, linenr, linenr+1)
310+
local virtual_lines = {}
281311
for _, s in pairs(out_table) do
282-
fn.append(linenr, s)
283-
linenr = linenr + 1
312+
local vline = {{ s, "MdEvalLine" }}
313+
table.insert(virtual_lines, vline)
284314
end
315+
vim.api.nvim_buf_set_extmark(bufnr, ns_id, linenr, 0, {
316+
virt_lines = virtual_lines,
317+
virt_lines_above = true,
318+
})
285319
end
286320

287321
-- Parses start line to get code of the language.
@@ -427,7 +461,16 @@ function M:eval_clean_results()
427461
print("Not inside a code block.")
428462
return
429463
end
464+
430465
remove_previous_output(linenr_until + 1)
466+
467+
-- clean virt text (block)
468+
local bufnr = vim.api.nvim_get_current_buf()
469+
local ns_id = vim.api.nvim_create_namespace("mdeval")
470+
remove_virtual_lines(bufnr, ns_id, linenr_until, linenr_until+1)
471+
472+
-- INFO: if it were to delete all virt text, it would be like:
473+
-- delete_existing_lines(bufnr, ns_id, 0, vim.api.nvim_buf_line_count(0))
431474
end
432475

433476
M.opts = defaults

0 commit comments

Comments
 (0)