Created
December 9, 2022 07:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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