ardumont / markdown-toc

Generate a TOC in markdown file
GNU General Public License v3.0
127 stars 102 forks source link

update TOC on save #47

Open VladimirAlexiev opened 4 years ago

VladimirAlexiev commented 4 years ago

I always forget to call markdown-toc-generate-or-refresh-toc before I save (half my commits just say "TOC" ;-))

So I wrote this little function

(defun my-markdown-toc-refresh ()
  "Refresh markdown TOC if present in the document."
  (interactive)
  (when (memq major-mode '(markdown-mode gfm-mode))
    (require 'markdown-toc)
    (when (markdown-toc--toc-already-present-p)
      (markdown-toc-generate-toc t))))
(add-hook 'before-save-hook #'my-markdown-toc-refresh)

(Note: #41 mentions updateOnSave as a feature of Atom and VSCode)

pierre-rouleau commented 3 years ago

@VladimirAlexiev ,

If you want to restrict your hook for saving files in markdown-mode, not all files as your code currently does, you would have to use a 2-step approach like the following:

(add-hook 'markdown-mode-hook
                   (lambda ()
                       (add-hook 'before-save-hook #'my-markdown-toc-refresh nil :local)))

The add-hook function has the LOCAL argument which must be set to non-nil to modify the hook's buffer-local value.

goetzc commented 2 years ago

Thanks @pierre-rouleau. This works perfectly:

(add-hook 'markdown-mode-hook
          (lambda ()
            (add-hook 'before-save-hook #'markdown-toc-refresh-toc)
            ))