Here is an updated version of the Header: Toggle Level commands.
This is derived from the “built-in” /h1-/h5 slash commands and added the part to handle the toggling off. More straightforward and still retains all the functions.
-- function to toggle a specific header level
local function toggleHeader(level)
local line = editor.getCurrentLine()
local text = line.textWithCursor
-- Detect current header level
local currentLevel = string.match(text, "^(#+)%s*")
currentLevel = currentLevel and #currentLevel or 0
local cleanText = string.gsub(text, "^#+%s*", "")
-- Toggle: remove if same, otherwise set new level
if currentLevel == level then
editor.replaceRange(line.from, line.to, cleanText, true)
else
editor.replaceRange(line.from, line.to, string.rep("#", level) .. " " .. cleanText, true)
end
end
-- register commands Ctrl-1 → Ctrl-6
for lvl = 1, 6 do
command.define {
name = "Header: Toggle Level " .. lvl,
key = "Ctrl-" .. lvl,
run = function() toggleHeader(lvl) end
}
end