Skip to content

Instantly share code, notes, and snippets.

@maxandron
Created December 9, 2022 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxandron/8e08400309cae99860f170cea3e5f5f3 to your computer and use it in GitHub Desktop.
Save maxandron/8e08400309cae99860f170cea3e5f5f3 to your computer and use it in GitHub Desktop.
A snippet that defines a `MarkdownTOC` command that creates a table of contents in the current markdown file at the cursor. nothing fancy
vim.api.nvim_create_user_command("MarkdownTOC", function()
if vim.bo.filetype ~= "markdown" then
print("This is not a markdown file")
return
end
-- Extract the hashtags using grep
local hashtags = vim.fn.systemlist("grep -oE '^#+.*' " .. vim.fn.expand("%"))
local toc = ""
for _, hashtag in ipairs(hashtags) do
-- the level determines the number of spaces before the list element (based on the amount of hashtags)
local level = string.len(string.match(hashtag, "^#+"))
local text = string.match(hashtag, "^#+%s*(.*)%s*$")
local anchor = string.lower(string.gsub(text, "%s+", "-"))
-- level is decreased by one because we want to start at root level
toc = toc .. string.rep(" ", level - 1) .. "- [" .. text .. "](#" .. anchor .. ")\n"
end
vim.api.nvim_paste(toc, true, -1)
end, { nargs = 0 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment