Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update TOC on save #47

Open
VladimirAlexiev opened this issue Aug 31, 2020 · 2 comments
Open

update TOC on save #47

VladimirAlexiev opened this issue Aug 31, 2020 · 2 comments

Comments

@VladimirAlexiev
Copy link

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
Copy link
Contributor

@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
Copy link

goetzc commented Jan 18, 2022

Thanks @pierre-rouleau. This works perfectly:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants