Skip to content

Commit

Permalink
feat: highlight code chunks in quarto ft
Browse files Browse the repository at this point in the history
without plugins
  • Loading branch information
jmbuhr committed Apr 11, 2024
1 parent 67a6e8e commit f67ef52
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion ftplugin/quarto.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
local api = vim.api
local ts = vim.treesitter

vim.b.slime_cell_delimiter = '```'
vim.b['quarto_is_r_mode'] = nil
vim.b['reticulate_running'] = false
Expand All @@ -13,7 +16,61 @@ vim.wo.showbreak = '|'
vim.api.nvim_buf_set_var(0, 'did_ftplugin', true)

-- markdown vs. quarto hacks
local ns = vim.api.nvim_create_namespace 'quartoHighlight'
local ns = vim.api.nvim_create_namespace 'QuartoHighlight'
vim.api.nvim_set_hl(ns, '@markup.strikethrough', { strikethrough = false })
vim.api.nvim_set_hl(ns, '@markup.doublestrikethrough', { strikethrough = true })
vim.api.nvim_win_set_hl_ns(0, ns)

-- highlight code cells similar to
-- 'lukas-reineke/headlines.nvim'
-- (disabled in lua/plugins/ui.lua)
local buf = api.nvim_get_current_buf()

local parsername = 'markdown'
local parser = ts.get_parser(buf, parsername)
local tsquery = '(fenced_code_block)@codecell'

-- vim.api.nvim_set_hl(0, '@markup.codecell', { bg = '#000055' })
vim.api.nvim_set_hl(0, '@markup.codecell', {
link = 'CursorLine',
})

local function clear_all()
local all = api.nvim_buf_get_extmarks(buf, ns, 0, -1, {})
for _, mark in ipairs(all) do
vim.api.nvim_buf_del_extmark(buf, ns, mark[1])
end
end

local function highlight_range(from, to)
for i = from, to do
vim.api.nvim_buf_set_extmark(buf, ns, i, 0, {
hl_eol = true,
line_hl_group = '@markup.codecell',
})
end
end

local function highlight_cells()
clear_all()

local query = ts.query.parse(parsername, tsquery)
local tree = parser:parse()
local root = tree[1]:root()
for _, match, _ in query:iter_matches(root, buf, 0, -1, { all = true }) do
for _, nodes in pairs(match) do
for _, node in ipairs(nodes) do
local start_line, _, end_line, _ = node:range()
pcall(highlight_range, start_line, end_line - 1)
end
end
end
end

highlight_cells()

vim.api.nvim_create_autocmd({ 'ModeChanged', 'BufWrite' }, {
group = vim.api.nvim_create_augroup('QuartoCellHighlight', { clear = true }),
buffer = buf,
callback = highlight_cells,
})

0 comments on commit f67ef52

Please sign in to comment.