I was having a “productive conversation” with ChatGPT today and after a couple of back and forth, together we cooked up these two little handy Shortcut-Commands:
First one is to toggle h1-h6 level headers with one convenient combo-keypress (Ctrl-1 to Ctrl-6):
-- function to toggle a specific header level
local function toggleHeader(level)
local line = editor.getCurrentLine()
-- handle empty line
if not line or not line.text then
editor.insertAtCursor(string.rep("#", level) .. " ")
return
end
local s, from, to = line.text, line.from, line.to
local prefix, rest = s:match("^(#+)%s+(.*)")
local currentLevel = prefix and #prefix or 0
local newLine
if currentLevel == level then
newLine = rest or s -- remove header
else
newLine = string.rep("#", level) .. " " .. (rest or s) -- set header to desired level
end
editor.replaceRange(from, to, newLine)
editor.moveCursor(from + #newLine, false)
end
-- register commands Ctrl-1 → Ctrl-6
for lvl = 1, 6 do
command.define {
name = "Header: Toggle Level - h" .. lvl,
key = "Ctrl-" .. lvl,
run = function() toggleHeader(lvl) end
}
end
The second one to rotate header level between [ h1-h2-h3-h4-h6-off ] using Ctrl-Shift-Tab:
command.define {
name = "Header: Rotate level",
key = "Ctrl-Shift-Tab",
run = function()
local line = editor.getCurrentLine()
-- If the line is completely empty (or nil), insert "# " at cursor
if not line or not line.text then
local cursor = editor.getCursor() or 0
editor.insertAtCursor("# ")
return
end
-- Normal case
local s, from, to = line.text, line.from, line.to
local hashes, rest = s:match("^(#+)%s+(.*)")
local level = hashes and #hashes or 0
local newLine = level < 6 and string.rep("#", level + 1) .. " " .. (rest or s) or (rest or s)
editor.replaceRange(from, to, newLine)
editor.moveCursor(from + #newLine, false)
end
}
Feel free to modify the Shortcut keys to your liking, also i am not a coder or a developer so you can also comment and/or improve the script itself, and also leave some feedback if you think it´s useful for you or not ![]()