Plugins
<actions>
<group id="MarkdownToc" text="Markdown Table of Contents">
<action id="GenerateMarkdownToc" class="com.example.GenerateMarkdownTocAction" text="Generate Table of Contents" />
</group>
</actions>public class GenerateMarkdownTocAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
// Get the current editor and file
Editor editor = FileEditorManager.getInstance(e.getProject()).getSelectedTextEditor();
VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument());
// Generate the table of contents
String toc = generateTableOfContents(file);
// Insert the table of contents into the editor
editor.getDocument().insertString(editor.getCaretModel().getOffset(), toc);
}
private String generateTableOfContents(VirtualFile file) {
// Read the contents of the file
String text = VfsUtil.loadText(file);
// Parse the headers and generate the table of contents
String[] lines = text.split("\n");
StringBuilder toc = new StringBuilder();
int level = 0;
for (String line : lines) {
if (line.startsWith("#")) {
// Get the header level
int headerLevel = line.indexOf(" ");
if (headerLevel > level) {
// Start a new sublist
toc.append("\n");
toc.append(" ".repeat(headerLevel - level));
toc.append("- ");
} else if (headerLevel == level) {
// Add a new item to the current list
toc.append("\n");
toc.append(" ".repeat(headerLevel));
toc.append("- ");
} else {
// End the current sublist and start a new one
toc.append("\n");
toc.append(" ".repeat(level - headerLevel));
toc.append("}\n");
toc.append(" ".repeat(headerLevel - level));
toc.append("- ");
}
// Add the header text
String headerText = line.substring(headerLevel + 1);
toc.append("[");
toc.append(headerText);
toc.append("]");
toc.append("(#");
toc.append(headerText.toLowerCase().replaceAll(" ", "-"));
toc.append(")");
// Update the current header level
level = headerLevel;
}
}
// Return the table of contents
return toc.toString();
}
}Last updated