Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Last active July 5, 2019 13:00
Show Gist options
  • Save jackrusher/6480848 to your computer and use it in GitHub Desktop.
Save jackrusher/6480848 to your computer and use it in GitHub Desktop.
I like to know how many words are in my markdown files.
;; this function is included in modern emacs, but here it is in case you haven't upgraded
(defun count-words (start end)
"Count words between START and END.
If called interactively, START and END are normally the start and
end of the buffer; but if the region is active, START and END are
the start and end of the region. Print a message reporting the
number of lines, words, and chars.
If called from Lisp, return the number of words between START and
END, without printing any message."
(interactive (list nil nil))
(cond ((not (called-interactively-p 'any))
(let ((words 0))
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(while (forward-word 1)
(setq words (1+ words)))))
words))
((use-region-p)
(call-interactively 'count-words-region))
(t
(count-words--buffer-message))))
(defvar wordcount-timer nil
"Timer to kick off word count recomputation.")
(defvar wordcount-current-count 0
"The result of the last word count.")
(defun wordcount-update-word-count ()
"Recompute the word count."
(setq wordcount-current-count (count-words (point-min) (point-max))))
(define-minor-mode wordcount-mode
"Toggle wordcount mode.
With no argument, this command toggles the mode.
A non-null prefix argument turns the mode on.
A null prefix argument turns it off.
When enabled, the word count for the current buffer
is displayed in the mode-line."
:init-value nil
:lighter (:eval (format " [%d words]" wordcount-current-count))
(if wordcount-mode
(progn
(set (make-local-variable 'wordcount-current-count)
(count-words (point-min) (point-max)))
(set (make-local-variable 'wordcount-timer)
(run-with-idle-timer 3 't #'wordcount-update-word-count)))
(cancel-timer wordcount-timer)))
(add-hook 'markdown-mode-hook (lambda () (wordcount-mode)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment