Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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))
(narrow-to-region start end)
(goto-char (point-min))
(while (forward-word 1)
(setq words (1+ words)))))
(call-interactively 'count-words-region))
(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
(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